我坚持以下几点:
脚本返回任意数字n
或数组,如下所示:
[["a"], ["b"], ["c"], ["d"]]
我需要使用promise then()
循环遍历数组,但由于我不知道会有多少元素,所以我最终会这样做:
var bundle_list = [["a"], ["b"], ["c"], ["d"]];
var x = bundle_list.reduce(function(current, next) {
console.log(current);
// requestBundle will also return a promise
return requestBundle(current)
.then(function(bundle_response) {
// do foo
console.log("CALLING NEXT")
console.log(next);
return RSVP.resolve(next);
});
})
x.then(function(last_response) {
return console.log("DONE")
});
我的问题是我的reduce/map
在我的异步代码运行之前都触发了所有迭代,所以我得到了current
控制台的3倍,然后是done
控制台。所以我的所有地图"循环"立即运行,结果稍后(稍后)计时......
我正在使用此RSVP实施,但它的A +应该不是问题。我一直在尝试提供here提供的答案,但我无法让它正常工作。
问题:
是否有可能创建一个" then-chain"具有任意数量的then
语句。如果是这样,一些指针值得赞赏!
谢谢!
答案 0 :(得分:8)
for(或forEach)循环应该:
var queue = RSVP.Promise.resolve(); // in ES6 or BB, just Promise.resolve();
bundle_list.forEach(function(el){
queue = queue.then(function(res){
console.log("Calling async func for", el);
return requestBundle(el);
});
});
queue.then(function(lastResponse){
console.log("Done!");
});