【问题标题】:async function doesn't wait of inside await in nodejs异步函数不会等待nodejs中的内部等待
【发布时间】:2021-02-25 20:40:43
【问题描述】:

我正在实现功能monthlyRevenue。 简单来说,就是返回月总收入,并接受站数组的参数,将产生收入,月份和年份。

问题 在这个函数内部,我有 getStationPortion,它将获取用户的收入部分。 所以我想让它像这样返回对象。

stationsPortion = {station1:30,station2:20}

在每月收入中

const stationPortions = await getStationPortions(stations)
console.log("portion map", stationPortions      //it will be shown very beginning with empty

getStationPortions

const getStationPortions = async (stations) => {
  let stationPortions = {}
  stations.map(async (value) => {
    const doc = await fdb.collection('Stations').doc(value).get()
    if (!doc.exists) {
      console.log("NO DOC")

    } else {
      stationPortions[value] = doc.data().salesPortion
      console.log(stationPortions)                   //it will be shown at the last.
    }
  })
  return stationPortions
}

我认为异步函数应该等待结果,但事实并非如此。 如果我的理解是错误的,我会感到困惑。 谢谢 (顺便说一下,fdb 是 firebase admin(firestore)

【问题讨论】:

  • 你甚至不应该在这里使用.map(),因为这看起来很简单。如果没有,你应该使用Promise.all()

标签: node.js async-await promise


【解决方案1】:

工作代码

const getStationPortions = async (stations) => {
  let stationPortions = {}
  await Promise.all(stations.map(async (value) => {
    const doc = await fdb.collection('Stations').doc(value).get()
    if (!doc.exists) {
      console.log("NO DOC")
    } else {
      stationPortions[value] = doc.data().salesPortion
      console.log(stationPortions)
    }
  }))
  return stationPortions
}
module.exports = router;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2020-09-23
    • 2019-06-16
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多