我想澄清这一点,因为文件不是很清楚;

Q1: Promise.all(iterable)是按顺序还是并行处理所有的promise ?或者,更具体地说,它相当于运行链式承诺

p1.then(p2).then(p3).then(p4).then(p5)....

或者它是某种其他类型的算法,其中所有的p1, p2, p3, p4, p5等同时(并行)被调用,并且结果在所有解决(或一个拒绝)后立即返回?

问题2:如果承诺。所有的运行都是并行的,是否有一种方便的方法来运行一个可迭代对象?

注意:我不想使用Q或蓝鸟,而是所有本地ES6规格。


当前回答

只是详细阐述一下@Bergi的回答(非常简洁,但很难理解;)

这段代码将运行数组中的每一项,并将下一个'then chain'添加到末尾:

function eachorder(prev,order) {
        return prev.then(function() {
          return get_order(order)
            .then(check_order)
            .then(update_order);
        });
    }
orderArray.reduce(eachorder,Promise.resolve());

其他回答

也可以使用递归函数用异步函数顺序处理可迭代对象。例如,给定一个数组a,使用异步函数someAsyncFunction()处理:

var a = [1, 2, 3, 4, 5, 6] function someAsyncFunction(n) { return new Promise((resolve, reject) => { setTimeout(() => { console.log("someAsyncFunction: ", n) resolve(n) }, Math.random() * 1500) }) } //You can run each array sequentially with: function sequential(arr, index = 0) { if (index >= arr.length) return Promise.resolve() return someAsyncFunction(arr[index]) .then(r => { console.log("got value: ", r) return sequential(arr, index + 1) }) } sequential(a).then(() => console.log("done"))

只是详细阐述一下@Bergi的回答(非常简洁,但很难理解;)

这段代码将运行数组中的每一项,并将下一个'then chain'添加到末尾:

function eachorder(prev,order) {
        return prev.then(function() {
          return get_order(order)
            .then(check_order)
            .then(update_order);
        });
    }
orderArray.reduce(eachorder,Promise.resolve());

并行

await Promise.all(items.map(async (item) => { 
  await fetchItem(item) 
}))

优点:速度更快。所有的迭代都将启动,即使其中一个在以后失败。然而,它会“快速失败”。使用的承诺。allsettle,即使某些迭代失败,也要并行地完成所有迭代。从技术上讲,这些是并发调用,而不是并行调用。

按顺序

for (const item of items) {
  await fetchItem(item)
}

优点:循环中的变量可以在每次迭代中共享。行为类似于普通的命令式同步代码。

平行

请看这个例子

const resolveAfterTimeout = async i => {
  return new Promise(resolve => {
    console.log("CALLED");
    setTimeout(() => {
      resolve("RESOLVED", i);
    }, 5000);
  });
};

const call = async () => {
  const res = await Promise.all([
    resolveAfterTimeout(1),
    resolveAfterTimeout(2),
    resolveAfterTimeout(3),
    resolveAfterTimeout(4),
    resolveAfterTimeout(5),
    resolveAfterTimeout(6)
  ]);
  console.log({ res });
};

call();

通过运行代码,它将控制台“CALLED”为所有六个承诺,当他们被解决,它将控制台每6个响应超时后,在同一时间

你可以通过for循环来实现。

Async函数返回承诺:

async function createClient(client) {
    return await Client.create(client);
}

let clients = [client1, client2, client3];

如果你写下面的代码,那么客户端是并行创建的:

const createdClientsArray = yield Promise.all(clients.map((client) =>
    createClient(client);
));

但是如果你想按顺序创建客户端,那么你应该使用for循环:

const createdClientsArray = [];
for(let i = 0; i < clients.length; i++) {
    const createdClient = yield createClient(clients[i]);
    createdClientsArray.push(createdClient);
}