生成器 + 承诺并行化 N 个项目

generators + promises to parallelize N number of items

挑战:

  1. 我们想为一个项目的子项发出 N 个并行 ajax 请求。
  2. 在 returning 之后,我们希望按顺序 (1...N) 处理它们
  3. 我们不想等待对 return 的所有承诺,但我们希望在它们返回时按顺序处理它们。

例如:

即使2,3,5先于1返回,我们也应该保留2,3,5的结果,在1的return之后,依次处理1,2,3(并等待4 在 5 之前回来)

工具:Q + ES6 生成器

使用占位符变量创建长度为 N-1 的数组

EG 当 N = 3 时:

let [N1,N2,N3] = yield [ Promise1, Promise2, Promise3 ]

//process items sequentially:
   console.log(N1)
   console.log(N2)
   console.log(N3)

但是,填充空变量数组似乎当然不起作用,因为引用不知道在哪里可以找到 var 声明

for(var i = 0; i< 3; i++) {
   res.push("some empty var")
}

考虑到坚持使用所提供工具的限制,我们如何并行化调用,但按顺序处理它们的 return?

您可以使用Promise.all().then()

javascript 在回答 returns 问题

中描述的确切结果
  1. We want to make N parallel ajax requests for an item's children.
  2. Upon returning, we want to process them in sequential order (1...N)
  3. We do NOT want to wait for all promises to return, but we want to process them IN ORDER as they come back. how could we parallelize calls, but process their returns sequentially?

您可以使用 .then() 链接到原始函数,其中 returns 一个承诺或 Promise 对象本身在 returning 值按顺序处理之前处理承诺在 .then() 传递给 Promise.all() 的参数链接到 Promise.all()

var n = 0;
var fn = function() {
  return new Promise(function(resolve, reject) {
    console.log("promise " + ++n + " called");
    setTimeout(function(i) {
      resolve(i)
    }, Math.random() * 2500, n)
  })
  // handle requirement 3. here
  .then(function(res) {
    console.log(res);
    return res
  })
}

Promise.all([fn(), fn(), fn()]) // handle requirement 1. here
// handle requirement 2. here
.then(function(data) {
    let [N1, N2, N3] = data;
    console.log(N1, N2, N3);
})

您可以通过等待循环内的下一个承诺来做到这一点:

const promises = […]; // or created programmatically
for (const promise of promises) {
    const result = yield promise; // await them sequentially
    console.log(result);
}