This is the code where I'm calling a function
masterCredsResponse.data.forEach((masterCred) => {
// Check Login status
masterCredsArray.push({
master: masterCred.parent,
loginCheck: Promise.resolve(getSessionID()())
})
})
Here I get
loginCheck: Promise { <pending> }
I'm seeing a lot of questions on this topic but unable to understand how to get it done. When I don't use loop but call it separately then it works like
let loginCheckReponse = await getSessionID()()
But i use this method in a loop that doesn't work
loginCheck: await getSessionID()() // Doesn't work
CodePudding user response:
@Samathingamajig is right about Promise.resolve. Also, you can't run await inside of the forEach without making the callback async.
The most basic fix would be adding an async to the callback and an await to the promise. But you then wouldn't be able to ergonomically wait for the array to finish processing.
masterCredsResponse.data.forEach(async (masterCred) => {
masterCredsArray.push({
master: masterCred.parent,
loginCheck: Promise.resolve(getSessionID())
})
})
You can use map and Promise.all to make sure you block execution properly. Note that they will all occur in parallel:
const masterCredPromises = masterCredsResponse.data.map(
async (masterCred) => ({
master: masterCred.parent,
loginCheck: await getSessionId()
})
);
const masterCredsArray = await Promise.all(masterCredPromises);
Hope that helps!
CodePudding user response:
masterCredsResponse.data.forEach( async (masterCred) => {
let loginCheckReponse = await getSessionID()()
// Check Login status
masterCredsArray.push({
master: masterCred.parent,
loginCheck: loginCheckReponse
})
})
