skip to Main Content

I am doing several 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

The problem is the log return response is being called first then manipulated data.

How can I assure to run all fetch’s before the function return the complete result?

PS: I have done with then() and await.

2

Answers


  1. To ensure all the fetch operations complete before returning the response, use Promise.all with await on an array of fetch promises. This will wait for all fetch operations to finish before proceeding

    Login or Signup to reply.
  2. The issue you’re facing is due to the asynchronous nature of JavaScript and the fact that fetch returns a Promise. One way is to use Promise.all to wait for all the promises generated by the fetch requests to be resolved.

    Example:

    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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search