如何使用map或reduce对任意数量的链元素运行promise-then链?

fre*_*ent 8 javascript asynchronous mapreduce promise rsvp-promise

我坚持以下几点:

脚本返回任意数字n或数组,如下所示:

[["a"], ["b"], ["c"], ["d"]]
Run Code Online (Sandbox Code Playgroud)

我需要使用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")
});
Run Code Online (Sandbox Code Playgroud)

我的问题是我的reduce/map两个都在我的异步代码运行之前触发所有迭代,所以我得到3倍的current控制台,然后是done控制台.所以我的所有地图"循环"都会立即运行,结果会稍后(稍后)计时...

我正在使用这个RSVP实现,但它是A +所以不应该是一个问题.我一直在努力解决这里提供的答案,但我无法让它正常工作.

问题:
是否可以使用任意数量的then语句创建"then-chain" .如果是这样,一些指针表示赞赏!

谢谢!

Ben*_*aum 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!");
});
Run Code Online (Sandbox Code Playgroud)