1

I've this function with map, how can call only when finish?

 _.map(data,async function (el) {
        if(Number.parseInt(el) != NaN && (el != null) && !isNaN(el)){
            console.log('ID: ' + el)
            await scrapeDetails(el) // <--- need to wait finish and than go to next element in map
        }
    })

async function scrapeDetails(id){
// ... bla bla
}
Mariano
  • 473
  • 3
  • 12
  • Does this answer your question? [Async Await map not awaiting async function to complete inside map function before mapping next item](https://stackoverflow.com/questions/64978604/async-await-map-not-awaiting-async-function-to-complete-inside-map-function-befo) – Timur Apr 12 '22 at 15:00

3 Answers3

0

map and other higher order functions have funky behaviors when given async...await functions. The best solution I found so far is using the for...of syntax with await. Something like this:

for (const element of data) {
  // do all operations here
}
Gabriel Lupu
  • 1,397
  • 1
  • 13
  • 29
0

Collect the promises and resolve them with Promise.all(). They're all done when that's done.

const promises = _.map(data, function (el) {
    if(Number.parseInt(el) != NaN && (el != null) && !isNaN(el)){
        console.log('ID: ' + el)
        return scrapeDetails(el)
    } else {
        return Promise.resolve();
    }
});

let allResults = await Promise.all(promises);
console.log('now we are done!')
danh
  • 62,181
  • 10
  • 95
  • 136
-2

Or you can always use recursion.

const asyncProcess = async (array, index) => {
  const value = array[index];
  if (!value) return;
  ..
  await scrapeDetails(el);
  return asyncProcess(array, index + 1);
}
Vijay Dev
  • 1,024
  • 7
  • 14