在promise库 Q中 ,您可以执行以下操作以顺序链接promise:
var items = ['one', 'two', 'three']; var chain = Q(); items.forEach(function (el) { chain = chain.then(foo(el)); }); return chain;
但是,以下命令不适用于 $ q :
var items = ['one', 'two', 'three']; var chain = $q(); items.forEach(function (el) { chain = chain.then(foo(el)); }); return chain;
只需使用$ q.when()函数:
var items = ['one', 'two', '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', 'two', 'three']; var chain = $q.when(); items.forEach(function (el, i) { chain = chain.then(foo(el, (items.length - i)*1000)); }); return chain;