【问题标题】:Async/await function is returning "undefined" instead of expected String value异步/等待函数返回“未定义”而不是预期的字符串值
【发布时间】:2021-11-17 06:46:47
【问题描述】:

我正在尝试学习如何使用异步函数。我在下面有我的代码。有两个功能。第一个 apiAddTask 调用第二个函数 SchedulesDAO.GetScheduleByTitle。这两个函数都是静态异步函数,调用 GetScheduleByTitle 函数时使用“await”。

在 GetScheduleByTitle 函数中,我从 Mongo 数据库中获取所需的 ID。该函数正确地获取了 ID,但没有返回它。相反,它返回未定义。

apiAddTask 函数:

static async apiAddTask(req, res, next){
    try{
        let taskFrequency = null
        const taskTitle = req.body.title
        const taskRepeat = req.body.repeat 
        if (taskRepeat == true){
            taskFrequency = req.body.frequency 
        }
        const taskStart = req.body.startdate
        const taskEnd = req.body.enddate 
        let taskSchedule = await SchedulesDAO.GetScheduleByTitle(req.body.schedule) //CALL TO GETSCHEDULESBYTITLE <--

        console.log(taskSchedule) // THIS PRINTS UNDEFINED                <------------

        const addResponse = await SchedulesDAO.addTask(
            taskTitle, taskRepeat, taskFrequency, taskStart, taskEnd, taskSchedule
        )
        res.json({status:"success"})
    }catch(e){
        res.status(500).json({error: e.message})
    }
}

GetScheduleByTitle 函数:

static async GetScheduleByTitle(title) {
    let query = {title: title} 
    let idString = ""
    let cursor

    try{
        cursor = await schedules.find(query)
    }catch (e) {
        console.error("Unable to issue find command: " + e)
        return {schedule: []}
    }
     
    cursor.toArray(function(err, results){
        console.log(results[0]._id.toString()) //THIS PRINTS THE RIGHT ID STRING    <-------------

        idString = results[0]._id.toString()
        return idString
    })

}

我无法弄清楚我到底错过了什么。请让我知道查看任何其他代码是否会有所帮助。

【问题讨论】:

  • 你的方法都没有返回值,所以输出 null 也就不足为奇了。

标签: node.js asynchronous async-await


【解决方案1】:

您的大部分代码都很好。问题在于您在 GetScheduleByTitle 函数中使用了回调:

async function () {
    cursor.toArray(function(err, results){
        console.log(results[0]._id.toString()) //THIS PRINTS THE RIGHT ID STRING    <-------------

        idString = results[0]._id.toString()
        return idString
    })
    // implicit return undefined
}

正在发生的事情是您的cursor.toArray() 正在被调用,正如您所期望的那样,但它会继续执行到隐式未定义的返回。在处理任何回调逻辑之前,您的函数会返回 undefined。

解决方法:

try {
    const results = await cursor.toArray()
    let idString = results[0]._id.toString()
    return idString
} catch (err) {
    console.trace(err)
    throw new Error(err)
}

使用基于异步承诺的方法。

如果不存在,您可以为仅回调函数创建一个包装器,如下所示:

const cursorToArray = async (cursor) => {
  return new Promise((resolve, reject) => {
    cursor.toArray(function(err, results){
      if (results)
        resolve(results)
      else
        reject(err)
    })
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2020-12-23
    • 2021-10-03
    • 2020-03-13
    • 2019-08-31
    相关资源
    最近更新 更多