-1

I've read of promises for maps but I can't seem to know how to implement it if the map is inside a function.

for Example:

async function1(){
  await mongoose.connect(CONNECTION_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });

  const account = await Account.find({
    priority: { $lt: 50000 },
  }).skip(i * 1000).limit(1000).sort("priority");

  const promise1 = await account.map(async (item) => {
    //make axios requests here
  }

  Promise.allSettled(promise1).then(()=> process.exit(0))
}

However, I have this code wherein the map is inside a for loop.

async function1(){
  await mongoose.connect(CONNECTION_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });

  //axios requests
  for (let i=0; i<50; i++){
    const account = await Account.find({
      priority: { $lt: 50000 },
    })
      .skip(i * 1000)
      .limit(1000)
      .sort("priority");

    await account.map(async (item) => {
      //make axios requests here
    }
  }

  //should wait for the map inside the loop to finish before executing
  process.exit(0)
}
Rane
  • 136
  • 2
  • 7
  • You can't await the `map()` (map isn't async/doesn't return a promise) but you can return an array full of promises from map and then `await` the Promise.all – pilchard Nov 25 '21 at 08:51
  • You can't `await` inside for loop. Consider using `await for` instead [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) – n1md7 Nov 25 '21 at 09:20
  • Does this answer your question? [Best way to call an asynchronous function within map?](https://stackoverflow.com/questions/33438158/best-way-to-call-an-asynchronous-function-within-map) – jonrsharpe Nov 25 '21 at 09:57
  • Partly. That question is for a promise in a map. My question is for a promise in a map in a for loop. – Rane Nov 27 '21 at 12:06

3 Answers3

4

You can not control asynchronous code in .map, period.

To await all promises you can do

  await Promise.all(account.map(async () => {
    // do your async thing
  }));

This reads "map to promises, then await all of them".

joegomain
  • 536
  • 1
  • 5
  • 22
1

You can do something like this

let url = 'https://jsonplaceholder.typicode.com/posts/'

async function getAll(){
    
    for(let i=0;i<5;i++){
        await Promise.all([...Array(5)].map(async (_,j) => {
            const res = await fetch(url+i+'+'+j)
            console.log(i,j,res.data);
        }));
        console.log("End of i loop index ",i);
    }
    
}
getAll()
Himanshu Singh
  • 1,803
  • 3
  • 16
0

The answer suggested by @joegomain is an effective way if in case your request to Axios depends on the response of another request in the map function

account.map(async (item) => {
  const { data } = await axios('/endpoint', options);
}