1

在这个问题中,我试图遍历从承诺中检索到的对象数组,并且对于数组中的每个对象,我想调用另一个承诺。一旦我调用了所有这些承诺,我想将 DONE 记录到控制台。

我如何知道所有的承诺何时完成?

function myFunction() {
  fetch("https://jsonplaceholder.typicode.com/albums").then(first_response => {
    first_response.json().then(function(value) {
      for (var i = 0; i < value.length; i++) {
        fetch("https://jsonplaceholder.typicode.com/users")
          .then(second_response => second_response.json())
          .then(value => console.log(value))
      }
      console.log("DONE!!");
    });
  });
}

myFunction();
.as-console-wrapper { max-height: 100% !important; top: 0; }

4

3 回答 3

0

用于Array.prototype.mapvalue数组转换为 Promises 数组,并调用.thenPromise.all数组的 。您还应该避免 Promise-as-callback 反模式,只需return将 Promise from one.then链接到 next .then,而不会创建不必要的嵌套:

function myFunction () {
  fetch("https://jsonplaceholder.typicode.com/albums")
    .then(first_response => first_response.json())
    .then(arr => Promise.all(arr.map(item => 
       fetch("https://jsonplaceholder.typicode.com/users")
       .then(second_response => second_response.json())
       .then(value => console.log(value))
      )))
    .then(() => {
      console.log("DONE!!");      
    });
}

myFunction();

请注意,您当前的代码在第一个响应中似乎没有使用任何东西,除了结果数组的长度,这很奇怪 - 如果您想使用您正在迭代的项目(创建新的 URL 来获取,例如),使用item上面映射函数中的变量。

于 2019-03-02T02:33:26.783 回答
0

您需要在数组中收集 Promise 并使用Promise.all(),以便在所有完成后提供回调。最简单的方法是将for循环更改为调用Array.prototype.map()

function myFunction() {
  fetch("https://jsonplaceholder.typicode.com/albums").then(first_response => {
    return first_response.json();
  }).then(function(value) {
    const promises = value.map((_, i) => {
      return fetch("https://jsonplaceholder.typicode.com/users")
        .then(second_response => second_response.json())
        .then(value => console.log(value))
    });
    return Promise.all(promises);
  }).then(() => console.log("DONE!!"));
}

myFunction();
.as-console-wrapper { max-height: 100% !important; top: 0; }

于 2019-03-02T02:37:18.203 回答
0

您可以使用 es6 feature promises 功能将所有 fetch 请求放在一起,如果所有 promises 都完成,那么您可以打印完成。

    function myFunction () {
  var promises = [];
  var promise = undefined;
   fetch("https://jsonplaceholder.typicode.com/albums").then(first_response => {
       first_response.json().then(function(value) {
            for (var i = 0; i < value.length; i++){
              promise = fetch("https://jsonplaceholder.typicode.com/users/?id="+value[i].id)
                  .then(second_response => second_response.json())
                  .then(value => console.log(value))   
              promises.push(promise)
            }
        Promise.all(promises).then(function(){ console.log("Done!");});
       });
   });
}

https://codepen.io/Shajith/pen/vPGGPJ?editors=0010

于 2019-03-02T03:14:30.487 回答