skip to Main Content

I’m trying to work with data sent from postman, array of objects.
I need to write all data into database, so I use mapping of array, and get undefined

const providers = await req.body.providers.map((provider) => {
    ProviderService.createProvider(provider.name, container._id);
});
Promise.all(providers).then((value) => {
    console.log(value);
});

I get from console log array of undefined, but items are creating in Data Base, I know I have mistake in asynchronous functions, but I don’t really understand – where

Thank you for answer

2

Answers


  1. if I got this right, when you use the await keyword inside async function you actually wait for the promise to be resolved then you assign its extracted value to the providers variable.
    Promise.all takes as parameter an array of promises, so I guess this is where things go wrong when you send it an array with values.

    Login or Signup to reply.
  2. Your first statement is returning an Array. You can only use await on promises.
    Promise.all() does return a promise though.

    So you just need to move the await to the correct place.

    const providers = req.body.providers.map((provider) => {
        ProviderService.createProvider(provider.name, container._id);
    });
    await Promise.all(providers).then((value) => {
        console.log(value);
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search