angularjs 如何动态地向队列中添加函数?

vs91vp4v  于 2023-01-20  发布在  Angular
关注(0)|答案(3)|浏览(155)

我有一个render(value)函数,我用不同的参数多次调用它。我需要链接对这个函数的调用,这样它只有在前一个调用完成后才开始执行。
我需要链接的函数返回一个promise:

function render(value){
   var deferred = $q.defer();

   /* Some logic here */

   return deferred.promise;
}

我应该在这里放什么?

function onClick(value){
   /*
       Add render(value) to the queue. And start execution if queue is empty
   */
}
htrmnn0y

htrmnn0y1#

这只是个链接-
正在创建队列:

var queue = $q.when();

添加要在队列上运行的函数:

queue = queue.then(function(){ // need to reassign since promises are immutable.
    console.log("Added!");
});

在你的例子中:

function onClick(value){
  queue = queue.then(function(){ return render(value); });
}
c9qzyr3d

c9qzyr3d2#

您可能想尝试以下方法:

var lastPromise;

function onClick(value) {
    var promise;

    if( lastPromise ) {
        promise = lastPromise.then(function() {
            return render(value);
        }).then(cleanup);
    }
    else {
        promise = render(value).then(cleanup);
    }

    lastPromise = promise;

    function cleanup() {
        if( promise === lastPromise ) {
            lastPromise = null;
        }
    }
}

lastPromise遵守了链接的最后承诺这确保了每个render()都将在前一个完成后运行。内部promise是“私有”承诺的概念。如果在解析时,私有承诺与上一个承诺相同,则将其清除。警告:未经测试!

rvpgvaaj

rvpgvaaj3#

人们搜索vanila javascript解决方案的queing函数和运行可以这样做

//Create function to return a promise
const waitForMe = (message) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(message);
    }, 2000);
  });
};

//define promise que
let queue = Promise.resolve();
//create function to que calls to waitFroMe from callers
const QueFunction = (message) => {
  queue = queue.then(async () => {
    console.log(await waitForMe(message));
  });
};

//call QuetFunction and watch each return promise after 2000 ms (2sec)
QueFunction("Promise 1");
QueFunction("Promise 2");

//or call from button click each click will be qued and executed
const btn = document.getElementById("btn_run");
btn.addEventListener("click", () => {
  QueFunction("Call from button click");
});

相关问题