0

Instead of getting values i get a pending Promise in my code:

let projects = [{ projectnr: null, contract: '4055' },
{ projectnr: '040200 FAS-U2', contract: '4056' },
{ projectnr: null, contract: '4057' }];

projects = (projects.map( async function(pro) {
            
            pro.articles = await ArticleService().getArticlesByRange(pro.contract);

            return pro;
        }))

const getArticlesByRange= async (contract) => {
        const db = await CompanyDbConnection.Get();
        const command = ArticleQueryService().getArticlesFromLagerInRange(contract);
        const result = await db.query(command);
        let articleResult = result.result;

        if (articleResult.length > 0) {
            articleResult = articleResult[0];
        }
        return articleResult;
    }

ArticleQueryService().getArticlesFromLagerInRange returns me a string query. The purpose is to assign the fetched data (array of numbers) to its project. Is map() the best way to do it?

moody
  • 404
  • 7
  • 19

1 Answers1

0

Use Promise.all to convert an array of Promises to a Promise of results

const response = Promise.all(projects.map(async function (project) {
   const { contract } = project;      
   const articles = await ArticleService().getArticlesByRange(contract);
   return { ...project, articles };
}))

I don't encourage you to mutate projects. It is best to have distinct snapshots of your state.

geoffrey
  • 2,080
  • 9
  • 13