美文网首页
Promise 静态 API 的使用方法

Promise 静态 API 的使用方法

作者: _扫地僧_ | 来源:发表于2022-08-15 10:07 被阅读0次

    Promise.all

    使用场景:假设我们希望许多 Promise 并行执行,并等待它们都准备好。

    一个实际例子是:并行下载多个 URL,并在这些 URL 全部下载完成后,再进行后续的业务逻辑处理。

    语法:

    let promise = Promise.all(iterable);
    

    Promise.all 接受一个 iterable 对象(通常是一组 Promise)并返回一个新的 Promise.

    当所有列出的 Promise 都 resolve 后,新的 Promise 也将 resolve,并且它们的结果数组成为新的 Promise 对象的结果。

    例如,下面的 Promise.all 在 3 秒后状态变为 fulfilled,然后它的结果是一个数组 [1, 2, 3]:

    Promise.all([
      new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
      new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
      new Promise(resolve => setTimeout(() => resolve(3), 1000))  // 3
    ]).then(alert); // 1,2,3 when promises are ready: each promise contributes an array member
    

    请注意,结果数组成员的顺序与其源承诺中的顺序相同。 尽管第一个 Promise 需要最长的时间来解决,但它仍然是结果数组中的第一个。

    一个常见的技巧是将一组作业数据映射到一组 Promise 中,然后将其包装到 Promise.all 中。

    例如,如果我们有一个 URL 数组,我们可以像这样获取它们:

    let urls = [
      'https://api.github.com/users/iliakan',
      'https://api.github.com/users/remy',
      'https://api.github.com/users/jeresig'
    ];
    
    // map every url to the promise of the fetch
    let requests = urls.map(url => fetch(url));
    
    // Promise.all waits until all jobs are resolved
    Promise.all(requests)
      .then(responses => responses.forEach(
        response => alert(`${response.url}: ${response.status}`)
      ));
    

    在调试器里,看到 requests 数组最开始的三个元素,状态全是 pending:

    看到 requests 变成 状态后,传入 then 的结果数组:

    一旦执行到 then 方法之后,状态变为 fulfilled:

    一个实际的使用 Promise.all 一次并发读取多个 Github user 记录的例子:

    let names = ['iliakan', 'remy', 'jeresig'];
    
    let requests = names.map(name => fetch(`https://api.github.com/users/${name}`));
    
    Promise.all(requests)
      .then(responses => {
        // all responses are resolved successfully
        for(let response of responses) {
          alert(`${response.url}: ${response.status}`); // shows 200 for every url
        }
    
        return responses;
      })
      // map array of responses into an array of response.json() to read their content
      .then(responses => Promise.all(responses.map(r => r.json())))
      // all JSON answers are parsed: "users" is the array of them
      .then(users => users.forEach(user => alert(user.name)));
    

    相关文章

      网友评论

          本文标题:Promise 静态 API 的使用方法

          本文链接:https://www.haomeiwen.com/subject/xxrcgrtx.html