如何在js的for循环中,顺序执行异步请求。

1,813 阅读1分钟

首先,对于连续发送HTTP请求返回的肯定是很难保证顺序,因为一个请求的成功有很多因素会被影响响应的时间。 当然,最简单的还是需要让异步同时完成以后,再统一通知。 大概步骤应该是: 所有HTTP请求都以 Promise 对象返回。 使用 Promise.all() 将将多个Promise实例,包装成一个新的Promise实例。 根据数据进行处理。 那么大概的代码差不多会是这样子:

function getInfo(info, index) {
  return new Promise((resolve, reject) => {
    // 使用settimeout模拟请求
    const ms = 1000 * Math.ceil(Math.random() * 3);
    setTimeout(() => {
      // get(info).save().then(data => { resolve(index); })
      resolve(index);
    }, ms);
    console.log(`${index} time: ${ms}`);
  });
}


let promises = [1, 2, 3].map((item, index) => {
  let info = {};
  return getInfo(info, index);
});


Promise.all(promises).then((allData) => {
  console.log(allData);
  // [0, 1, 2]
}).catch((err) => {
  console.log(err);
})