Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

node using await in for loop which calls an async function

I’m having a little trouble getting back a result from an async function I am calling in a for loop, I should be getting back a string but it is returning a promise instead
I am following this syntax but I haven’t been able to get it to work properly and I’m hoping for some insight into why this fails https://eslint.org/docs/rules/no-await-in-loop

here’s the function I am trying to work with, in this case decodeTheObject is async and returns a promise but if I use await decodeTheObject eslint will give me an error saying I can’t use await inside a for loop, unfortunately the workaround above still results in a promise being returned instead of a resolved value

async function decode (request, encodedObj) {
  const decodedArr = [];
  try{
    for (const id of encodedObj) {
      decodedArr.push({
        data: decodeTheObject(request, id), // this is an async function
        partial: true,
      });
    }
      await Promise.all(decodedArr);
      return decodedArr;

  }catch (err) {
    throwError(
      req,
      {
        errorDetails: [
          {
            issue: 'INVALID_ENCODING',
            description: 'Invalid encoded obj',
          },
        ],
      },
    );
  }
};


// ----- calling function -----

 const decodedObj = await decode(request, encodedItem);
  
  const payload = {
    newprop: decodedObj
  };



MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Promise.all() has to work directly on an array of promises. You are passing it an array of objects which won’t know how to reach into the objects to get the promises so thus, it won’t accomplish anything useful. There are a couple ways to approach this.

This will await each async call in sequence, get the value and push the value into the array:

async function decode (request, encodedObj) {
  const decodedArr = [];
  try{
    for (const id of encodedObj) {
      let data = await decodeTheObject(request, id);
      decodedArr.push({data, partial: true});
    }
    return decodedArr;
  } catch(e) {
     ...
  }
}

Or, you could run them in parallel with Promise.all() like this by creating an array of promises and using Promise.all() on that array:

async function decode (request, encodedObj) {
    return Promise.all(encodedObj.map(id => {
        return decodeTheObject(request, id).then(data => {
           return {data, partial: true};
        });
    })).catch(err => {
       ...
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading