2

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
  • what does *Doesn't work* mean? Please describe errors fully – Jaromanda X Nov 25 '22 at 06:47
  • Means it returns Promise { } – Iqra Moazzama Nov 25 '22 at 06:48
  • if `getSessionID()()` results in a Promise, then `Promise.resolve(getSessionID()())` doesn't do anything useful (like wait for it to settle) – Jaromanda X Nov 25 '22 at 06:48
  • You misunderstand what `Promise.resolve` does. It wraps an already found value inside of a new `Promise` that immediately `resolve`s, meaning the data is able to be accessed. It doesn't mean that it doesn't make it a `Promise` anymore. You still need to either `await` or `.then` the `Promise` – Samathingamajig Nov 25 '22 at 06:48
  • And then moves to next iteration without returning actual response from getSessionID func – Iqra Moazzama Nov 25 '22 at 06:49
  • 3
    the clue is where you say `then it works like` ... that's what you need to do in a `for` loop, not in a `forEach` callback – Jaromanda X Nov 25 '22 at 06:49
  • 1
    There is some good information about this here: https://stackoverflow.com/questions/40328932/javascript-es6-promise-for-loop – Boguz Nov 25 '22 at 07:04

2 Answers2

3

@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!

Jake Fried
  • 31
  • 3
1
masterCredsResponse.data.forEach( async (masterCred) => {
  let loginCheckReponse =  await getSessionID()()
  // Check Login status
  masterCredsArray.push({
    master: masterCred.parent,
    loginCheck: loginCheckReponse
  })
})
Rajan Karmaker
  • 118
  • 1
  • 7