【问题标题】:foreach loop with promise execute API call AFTER the first one is done第一个完成后,带有承诺执行 API 调用的 foreach 循环
【发布时间】:2021-01-02 06:33:03
【问题描述】:
let array = [1,2,3];
 array.forEach(function(item,index) {
   var data =  fetch('https://reqres.in/api/products/'+item);
   //wait for response after response come then next iterating a loop (first,second,third)
  
});

我想跑步

  1. 第一次调用api
  2. 等待回复
  3. 显示成html

但目前我的脚本调用所有 3 次 api 而无需等待响应

我想等待响应,完成后调用下一个 api ..就像那样

【问题讨论】:

  • 你可能想使用 async/await。 javascript.info/async-await
  • 您应该使用for of 循环或普通for 循环。异步/等待函数不能与 forEach 一起正常工作。

标签: javascript node.js angularjs promise async-await


【解决方案1】:

使用 for of 代替 forEach 循环并为这样的请求做出承诺

var items = [1, 2];
function makeRequest(index) {
 return new Promise((resolve, reject) => { 
  $.ajax({
    url: "https://reqres.in/api/products/"+index,
    type: "GET",
    success: function(response){
        console.log(response.data);
        resolve(response);
    },
    error: function (error) {
        reject(error)
    }
 })
})
}

async function runAsync(locations){
  for(let location of locations){
    console.log('value ' + location);
    await makeRequest(location);
  };
}

runAsync(items);

【讨论】:

    【解决方案2】:
    async function asyncExample() {
      let array = [1,2,3];
       for (let i = 0; i < array.length; i++) {
         var data = await fetch('https://reqres.in/api/products/'+item);   
       });
    }
    

    您必须使用 Async/Await 使代码等待 API 调用。 Async/await 不适用于循环,为避免出现问题,您应该使用普通的 forfor of。更多示例:https://zellwk.com/blog/async-await-in-loops/

    【讨论】:

      【解决方案3】:

      您需要同步 $http 调用。 Javascript 可以通过 Promises 做到这一点。

      var promise = new Promise(function(resolve, reject){ resolve("OK");});
      
      let array = [1,2,3];
       array.forEach(function(item,index) {
      
          promise.then(
              $http.get('https://reqres.in/api/products/'+item)
          ).then(function (response){
              ...
          });
      });         
      
      promise.catch(function(response) {
            ...
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-24
        • 1970-01-01
        • 1970-01-01
        • 2016-09-09
        • 2019-05-22
        • 2017-05-07
        • 2018-05-12
        相关资源
        最近更新 更多