我如何按序angularjs $ Q链的承诺? [英] How do I sequentially chain promises with angularjs $q?
本文介绍了我如何按序angularjs $ Q链的承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在承诺库的问:的,你可以做以下顺序链的承诺:
VAR项目= [一,二,三化];
VAR链= Q();
items.forEach(功能(EL){
链= chain.then(富致发光(EL));
});
返回链;
但是,下面不工作的 $ Q 的:
VAR项目= [一,二,三化];
VAR链= $ Q();
items.forEach(功能(EL){
链= chain.then(富致发光(EL));
});
返回链;
解决方案
只需使用$ q.when()函数:
VAR项目= [一,二,三化];
变种链= $ q.when();
items.forEach(功能(EL){
链= chain.then(富致发光(EL));
});
返回链;
注:富必须是一个工厂,例如
VAR项目= [一,二,三化];
变种链= $ q.when();
items.forEach(功能(EL,I){
链= chain.then(富致发光(EL(items.length - 我)* 1000));
});
返回链;功能setTimeoutPromise(毫秒){
变种延迟= $ q.defer();
的setTimeout(defer.resolve,MS);
返回defer.promise;
}函数foo(项目,MS){
返回功能(){
返回setTimeoutPromise(MS)。然后(函数(){
的console.log(项目);
});
};
}
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;
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;
解决方案
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;
Note: foo must be a factory, e.g.
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;
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);
});
};
}
这篇关于我如何按序angularjs $ Q链的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文