Home > Blockchain >  Promise returns undefined value from mapping
Promise returns undefined value from mapping

Time:11-15

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

CodePudding user response:

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.

CodePudding user response:

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);
});

  • Related