如何在JavaScript中使用Promise.all来等待多个承诺的解决?

137 阅读1分钟

在掌握了javascript中的异步编程后,你可能很快发现你需要等待多个异步任务的发生。输入Promise.all!

一个单一的承诺

首先,让我们做一个简单的fetch 请求,返回一个Promise 。我使用的是node runtime,所以我将使用node-fetch 包。在这个请求中,我们将只是从开放的github api中抓取一些关于我的github配置文件的信息。

const fetch = require('node-fetch');

fetch('https://api.github.com/users/nas5w')
  .then((res) => res.json())
  .then((user) => {
    console.log(user);
  });

果然,我们记录了我们的用户。

{
    login: 'nas5w',
    id: 7538045,
    node_id: 'MDQ6VXNlcjc1MzgwNDU=',
    avatar_url: 'https://avatars2.githubusercontent.com/u/7538045?v=4',
    etc.
}

多重承诺

这很好,但如果我们想获取两个不同的账户,并且只在两个请求都得到解决后才采取行动呢?

这时我们可以使用Promise.allPromise.all 接受一个承诺数组,并且只在数组中的所有承诺解决后执行提供给then 的函数。

它看起来会像这样。

Promise.all([promise1, promise2, promise3]).then((data) => {
  // Do something with array of resolved promises
});

在我们的fetch 例子中,我们可以获取关于nas5woctocat 两个账户的详细信息,并在两个承诺都解决后才记录这些详细信息。

const fetch = require('node-fetch');

function getAccount(id) {
  return fetch(`https://api.github.com/users/${id}`).then((res) => res.json());
}

const promise1 = getAccount('nas5w');
const promise2 = getAccount('octocat');

Promise.all([promise1, promise2]).then((users) => {
  console.log(users);
});

现在我们得到一个包含两个用户信息的数组,只有在两个获取请求都完成后才会记录。

[
  {
    login: 'nas5w',
    id: 7538045,
    node_id: 'MDQ6VXNlcjc1MzgwNDU=',
    avatar_url: 'https://avatars2.githubusercontent.com/u/7538045?v=4',
    etc...
  },
  {
    login: 'octocat',
    id: 583231,
    node_id: 'MDQ6VXNlcjU4MzIzMQ==',
    avatar_url: 'https://avatars3.githubusercontent.com/u/583231?v=4',
    etc...
  }
]