简体   繁体   English

无法解析 forEach 中的 Promise

[英]Unable to Resolve Promise in forEach

This is the code where I'm calling a function这是我调用 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

@Samathingamajig is right about Promise.resolve . @Samathingamajig 关于Promise.resolve是正确的。 Also, you can't run await inside of the forEach without making the callback async.此外,如果不使回调异步,则不能在forEach内部运行await

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.最基本的修复方法是向回调添加一个async并向 promise 添加一个await 。但是您将无法按照人体工程学等待数组完成处理。

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.您可以使用mapPromise.all来确保正确阻止执行。 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!希望有帮助!

masterCredsResponse.data.forEach( async (masterCred) => {
  let loginCheckReponse =  await getSessionID()()
  // Check Login status
  masterCredsArray.push({
    master: masterCred.parent,
    loginCheck: loginCheckReponse
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM