如何解决多次抓取的同步问题?

问题描述 投票:0回答:2

我正在做一些事情。

  let var1 = []
  let var2 = []

  await dateArray?.map((day) => {
    for (const o of myFirstList) {
      for (const d of mySecondList) {
        const resp = fetch(url-with-params)
          .then((resp) => resp.json())
          .then((data) => {
            const f = manipulateResponse(data)

            logger.info('1: manipulated data')

            var1.push(f.data1)
            var2.push(f.data2)
          })
      }
    }
  })

  logger.info('2: return response')
  let response = {
    var1,
    var2,
  }

  return response

问题是日志

return response
首先被调用,然后是
manipulated data

如何确保在函数返回完整结果之前运行所有 fetch?

PS:我已经完成了

then()
await

javascript async-await synchronization fetch
2个回答
0
投票

为了确保所有获取操作在返回响应之前完成,请在获取承诺数组上使用

Promise.all
await
。这将等待所有获取操作完成后再继续


0
投票

您面临的问题是由于 JavaScript 的异步特性以及 fetch 返回 Promise 的事实造成的。一种方法是使用

Promise.all
等待由获取请求生成的所有承诺得到解决。

示例:

let var1 = [];
let var2 = [];

// Create an array to store all the fetch promises
const fetchPromises = [];

await dateArray?.map((day) => {
  for (const o of myFirstList) {
    for (const d of mySecondList) {
      const respPromise = fetch(url-with-params)
        .then((resp) => resp.json())
        .then((data) => {
          const f = manipulateResponse(data);

          logger.info('1: manipulated data');

          var1.push(f.data1);
          var2.push(f.data2);
        });

      // Add the promise to the array
      fetchPromises.push(respPromise);
    }
  }
});

// Use Promise.all to wait for all fetch promises to resolve
await Promise.all(fetchPromises);

logger.info('2: return response');
let response = {
  var1,
  var2,
};

return response;
© www.soinside.com 2019 - 2024. All rights reserved.