【问题标题】:Looping through an array of objects, calling a promise for every object and logging when it's complete循环遍历一个对象数组,为每个对象调用一个promise并在它完成时记录
【发布时间】:2019-07-24 01:53:50
【问题描述】:

在这个问题中,我试图循环遍历从承诺中检索到的对象数组,以及我想要的数组中的每个对象 调用另一个承诺。一旦我调用了所有这些承诺,我想将 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; }

【问题讨论】:

    标签: javascript object ecmascript-6 promise es6-promise


    【解决方案1】:

    使用Array.prototype.mapvalue 数组转换为Promises 数组,并在该数组的Promise.all 上调用.then。您还应该避免 Promise-as-callback 反模式,只需 return 将 Promise 从一个 .then 链接到下一个 .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 变量。

    【讨论】:

    • 谢谢,是的。这很奇怪,这是我需要帮助的更大问题的一部分。实际上,我会将值传递给循环。
    • 任何答案对您有帮助吗?如果是这样,请考虑投票并接受其中之一,请参阅What should I do when someone answers my question? :)
    【解决方案2】:

    您需要在数组中收集承诺并使用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; }

    【讨论】:

      【解决方案3】:

      您可以使用 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

      【讨论】:

        猜你喜欢
        • 2020-06-22
        • 1970-01-01
        • 2018-09-04
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多