javascript – 异步/等待在foreach中不等待

参见英文答案 > Using async/await with a forEach loop                                    13个
我正在尝试在使用forEach循环的函数中使用async和await.恼人地说,我无法让它发挥作用.应该发生的是它需要一系列事件文档,循环遍历它们,添加一些额外的数据,然后将它们推送到events数组.然后从原始函数返回此事件数组.这是我的代码:

async function getEvents() {
  ...
  var events = []
  await addExtrasToDocsForUser(docs, currentUserId, events)
  return events

}


var addExtrasToDocsForUser = (docs, currentUserId, events) => {
    return docs.forEach(async (eventDoc) => {
        const event = await addExtrasToDocForUser(eventDoc, currentUserId)
        events.push(event)
    })
}

实际发生的是getEvents()函数在forEach循环完成之前将事件作为空数组返回.我该如何解决?

最佳答案
为什么要结合同步和异步功能?
您调用await addExtrasToDocsForUser(docs,currentUserId,events),但您的函数addExtrasToDocsForUser不是异步的.

var addExtrasToDocsForUser = async (docs, currentUserId, events) => {
  return await docs.forEach(async (eventDoc) => {
    const event = await addExtrasToDocForUser(eventDoc, currentUserId)
    events.push(event)
  })
}

你想做这样的事情:

var someOperation = async (op0, op1) => {
	return op0+':'+op1
}

var fnWithForeach = async (docs, number, outputs)=>{
  return await docs.forEach(async (doc)=>{
	const output = await someOperation(doc, number)
	outputs.push(output) 
  })
}

async function getOutputs() {
  // ...
  var docs = ['A', 'B', 'C']
  var number = 10
  // ...
  var outputs = []
  await fnWithForeach(docs, number, outputs)
  return outputs
}

async function main() {
  // ...
  var outputs = await getOutputs()
  console.log(outputs)
  // ...
}

main()

转载注明原文:javascript – 异步/等待在foreach中不等待 - 代码日志