即使使用异步,JS也会在循环结束之前返回

时间:2019-01-23 21:20:00

标签: javascript asynchronous

我正在尝试在循环之外获取我的obj的值,但是它似乎没有用。在下面附上我的代码示例,非常感谢您的帮助:)

const constructedTeams = {......
......
}; 
const obj = {}
let counter = 0
await Object.keys(constructedTeams).forEach(async key => {
  await constructedTeams[key].forEach(async (el, i) => {
    const members = await coreApi.getTeamMembersWithExtendedProperties(el.projectId, el.teamId);
    const temp = {}
    counter += 1
    const NameMembers = members.map(member => member.identity.displayName).join(', ')
    temp[el.teamName] = NameMembers
    if (!obj[key] || Object.keys(obj[key]).length == 0) {
      console.log(1)
      obj[key] = temp
    } else {
      console.log(0)
      Object.assign(obj[key], temp) 
    }
    console.log(`Object ${JSON.stringify(obj, null, 2)}`) // => return the actual object 
    // const NameMembers = await members.map(member => member.identity.displayName).join(', ')
  })
})
console.log(counter) // => return 0
console.log(`obj ${JSON.stringify(obj, null, 2)}`) // => return {}

0 个答案:

没有答案