如何解决具有多个获取的同步问题?

How to solve a sync problme with several fetch?

提问人:albertoivo 提问时间:11/6/2023 更新时间:11/6/2023 访问量:43

问:

我正在做几个fecth。

  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 responsemanipulated data

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

PS:我已经用和.then()await

javascript async-await 同步 获取

评论


答:

0赞 eugene musebe 11/6/2023 #1

要确保在返回响应之前完成所有 fetch 操作,请在 fetch promise 数组上使用 with。这将等待所有提取操作完成,然后再继续Promise.allawait

0赞 Bassam A. 11/6/2023 #2

您面临的问题是由于 JavaScript 的异步性质以及 fetch 返回 Promise 的事实。一种方法是等待 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;