gpt4 book ai didi

javascript - 如何判断Javascript Q deferred()是否已经执行完链中的所有函数

转载 作者:行者123 更新时间:2023-11-29 15:39:12 25 4
gpt4 key购买 nike

是否可以知道,当使用 Javascript Q promise 库执行链中注册的所有函数时?

我将从 here 发布示例代码(事实上​​我的问题是跟进):

testJSCallbacks();

function testJSCallbacks(){
var i = 0,
promise;

for (i = 0; i < 5; i++) {
//Make initial promise if one doesn't exist
if (!promise) {
promise = Q.fcall(getStep(i));
}
//Append to existing promise chain
else {
promise = promise.then(getStep(i));
}
//then function returns another promise that can be used for chaining.
//We are essentially chaining each function together here in the loop.
promise = promise.then(function (key) {
//Log the output of step here
console.log("Step 1 " + key);
return key;
})
//then function takes a callback function with one parammeter (the data).
//foo signature meets this criteria and will use the resolution of the last promise (key).
.then(foo)
//myCB will execute after foo resolves its promise, which it does in the onsuccess callback
.then(myCB);
}
}

function getStep(step) {
return function () {
return step;
}
}

function foo(key) {
//retrieve png image blob from indexedDB for the key 'key'. Assume that the database is
//created and started properly
var getRequest = transaction.objectStore("store").get(key),
//Need to return a promise
deferred = Q.defer();
getRequest.onsuccess = function (event) {
var result = event.target.result;
if(result){
console.log("Step 2 " + key + " Found");
}else{
console.log("Step 2 " + key + " not Found");
}
deferred.resolve(result);
}

return deferred.promise;
}

function myCB (result){
console.log("Step 3: " + result);
}

=============

如果您在代码中注意到 foo() 和 myCB() 都将执行 5 次。

我想知道的是,当函数 myCB() 上次执行时,是否有可能从 Q 库中获得回调或某种通知,本质上意味着队列是“空的”并且所有已注册/执行延迟函数?

提前致谢。

最佳答案

是的,有!哎呀 - 我什至可以说这就是 promise 的全部意义所在。

那个方法叫做drumroll .then!

使用它时,我们还将使用 Q.all 来等待 promise 集合。这是因为你有一个循环。如果你没有 - 我们只需要 .then

function testJSCallbacks(){
var promises = [];
for(var i = 0; i < 5; i++){
...
promise = promise.then(function (key) {
//Log the output of step here
console.log("Step 1 " + key);
return key;
})
//then function takes a callback function with one parammeter (the data).
//foo signature meets this criteria and will use the resolution of the last promise (key).
.then(foo)
//myCB will execute after foo resolves its promise, which it does in the onsuccess callback
.then(myCB);
promises[i] = promise;
}
return Q.all(promises); // note the return statement
}

然后,你可以 Hook 它的完成:

 testJSCallbacks().then(function(results){
// everything is complete and none of it rejected
});

如果你从这篇文章中得到一件事——它应该是从方法中返回 promise :)。此外,不是运行 myCb 而是简单地返回值并从外部运行 myCb - 它更强大:)

关于javascript - 如何判断Javascript Q deferred()是否已经执行完链中的所有函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22567446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com