0

I have a problem with async/await and some Promises.

I have this code. It starts here:

let valid = await LoadRouter.load(body); console.log(valid);//showing me Pending Promises 

The function is:

loadGeneratingUnits(data){ let newUGArray = []; try { const result = data.map(async (itemGU, index) => { const checGU = await this.checkDataGu(itemGU.nombre); if(!checGU){ let newUG = { generating_unit_name: itemGU.nombre, description: (!itemGU.descripcion) ? null : itemGU.descripcion, it_generating_unit_id: (!itemGU.it_unidad_generadora) ? 0 : itemGU.it_unidad_generadora } newUGArray.push(newUG); } }) return result; } catch (error) { throw new Error(error.message) } } 

This one is where I have the problems

async checkDataGu(guName = null){ if(guName){ return await generatingUnitModel.findOne({ attributes: [ 'id', 'generating_unit_name', ], where: { generating_unit_name: guName } }) } 

}

Any comment about the use of async/await on this code?

3
  • 1
    Try making loadGeneratingUnits async, wrap the data.map in a Promise.all and await its result Commented Jan 6, 2020 at 21:21
  • 1
    The .map is now returning an array of promises since the mapper function returns promises (it's async!) Commented Jan 6, 2020 at 21:21
  • It would also appear that the function does not returm newUGArray. Should it? Commented Jan 6, 2020 at 21:25

1 Answer 1

2

By making the callback to data.map() async, data.map() is now transforming the data into an array of Promises, because the return value of an async function is always a Promise. await only will wait for a Promise to resolve, not an array of them. You should use Promise.all for that:

 const result = Promise.all(data.map(async (itemGU, index) => { const checGU = await this.checkDataGu(itemGU.nombre); if(!checGU){ let newUG = { generating_unit_name: itemGU.nombre, description: (!itemGU.descripcion) ? null : itemGU.descripcion, it_generating_unit_id: (!itemGU.it_unidad_generadora) ? 0 : itemGU.it_unidad_generadora } newUGArray.push(newUG); } })) 

Now result is one Promise that will resolve with an array of the values each inner Promise resolved with. Ultimately this means your upper let valid = await LoadRouter.load(body); should resolve with the array you expect.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.