user15124758
user15124758

Reputation:

is there any possibility to use async/await with map,

I have an async function I have to call it under the map function,

class DataArticle {
id:number,
title:string,
...
user:User // User Entity 
}
 

I want to get articles then assign to each article the author of it:

var dtresult = this.articleRepo.findAll(); // get all articles 
const result:DataArticle[] = dtresult.map(async (a:DataArticle)  => { 
let user = await this.UserRepo.getUser(a.id)
a.user = user ; // assign user to the article after getting the user 
return a ;
 })

I tried implemeting async function with this way and it doesn't work

Upvotes: 1

Views: 51

Answers (1)

apple apple
apple apple

Reputation: 10614

You don't need to use another library for this task.

It can be achieved by Promise.All (or Promise.allSettled)

async function getUser(id){return id;}
let data = [...Array(10).keys()]


async function the_caller_function(){
   const result = await Promise.all(data.map(async a=> {
      let user = await getUser(a)
      return {user:a}
   }))
   console.log(result)
}

the_caller_function();

Upvotes: 1

Related Questions