在承诺图书馆Q中,您可以按照以下顺序链接承诺:
var items = ['one','two','three']; var chain = Q(); items.forEach(function (el) { chain = chain.then(foo(el)); }); return chain;
但是,以下内容不适用于$q:
var items = ['one','three']; var chain = $q(); items.forEach(function (el) { chain = chain.then(foo(el)); }); return chain;
只需使用$q.when()函数:
原文链接:https://www.f2er.com/angularjs/142410.htmlvar items = ['one','three']; var chain = $q.when(); items.forEach(function (el) { chain = chain.then(foo(el)); }); return chain;
注意:foo必须是工厂,例如
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','three']; var chain = $q.when(); items.forEach(function (el,i) { chain = chain.then(foo(el,(items.length - i)*1000)); }); return chain;