如何使用 angularjs $q 依次链接 promise? [英] How do I sequentially chain promises with angularjs $q?
本文介绍了如何使用 angularjs $q 依次链接 promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在promise库Q中,您可以执行以下操作来顺序链接promise:
In the promise library Q, you can do the following to sequentially chain promises:
var items = ['one', 'two', 'three'];
var chain = Q();
items.forEach(function (el) {
chain = chain.then(foo(el));
});
return chain;
但是,以下内容不适用于 $q:
however, the following doesn't work with $q:
var items = ['one', 'two', 'three'];
var chain = $q();
items.forEach(function (el) {
chain = chain.then(foo(el));
});
return chain;
推荐答案
只需使用 $q.when() 函数:
Simply use the $q.when() function:
var items = ['one', 'two', 'three'];
var chain = $q.when();
items.forEach(function (el) {
chain = chain.then(foo(el));
});
return chain;
注意:foo 必须是工厂,例如
Note: foo must be a factory, e.g.
function setTimeoutPromise(ms) {
var defer = $q.defer();
setTimeout(defer.resolve, ms);
return defer.promise;
}
function foo(item, ms) {
return function() {
return setTimeoutPromise(ms).then(function () {
console.log(item);
});
};
}
var items = ['one', 'two', 'three'];
var chain = $q.when();
items.forEach(function (el, i) {
chain = chain.then(foo(el, (items.length - i)*1000));
});
return chain;
这篇关于如何使用 angularjs $q 依次链接 promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文