【发布时间】:2014-04-29 07:59:42
【问题描述】:
有没有可能知道,当使用 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 库中获得某种回调或通知,本质上意味着队列是“空的”并且所有注册/执行延迟函数?
提前致谢。
【问题讨论】:
标签: javascript promise deferred q