You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Async/await函数返回undefined而非预期String值问题如何解决

问题原因

你的问题核心是GetScheduleByTitle函数混用了回调和Promise异步范式,没有正确等待查询结果返回就结束了函数执行:

  • MongoDB的cursor.toArray()同时支持回调和Promise两种调用方式,你当前使用的回调写法属于异步执行逻辑,外层的async函数不会等待回调执行完成,会直接走到函数末尾,没有显式返回值的情况下自然返回undefined
  • 你写在回调里的return idString只会将值返回给回调函数本身,不会作为外层GetScheduleByTitle函数的返回值

修复方案

将toArray的回调写法替换为await的Promise写法即可:

static async GetScheduleByTitle(title) {
    const query = {title: title} 
    try{
        const cursor = await schedules.find(query)
        // 用await替代回调等待查询结果返回
        const results = await cursor.toArray()
        // 新增空结果判断,避免数组为空时报错
        if(!results.length) return null
        const idString = results[0]._id.toString()
        console.log(idString)
        return idString
    }catch (e) {
        console.error("Unable to issue find command: " + e)
        return {schedule: []}
    }
}

修改后你在apiAddTask里拿到的taskSchedule就会是预期的ID字符串了。

内容的提问来源于stack exchange,提问作者user16988363

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:24:03