【问题标题】:Google Cloud / Firebase Functions: await is only valid in async functionGoogle Cloud / Firebase 函数:await 仅在异步函数中有效
【发布时间】:2019-10-07 02:07:40
【问题描述】:

我已经创建了这个函数:

async function getRoomTempFromRoomId(roomId) {
    const querySnapshot = await db.collection("sensors").where("room", "==", roomId).where("type", "==", "temperature").limit(1).get();
    var values = []
    values = querySnapshot.docs.map((doc) => { return doc.data().value });
    return values[0];
}

现在当我使用console.log(await getRoomTempFromRoomId("1234")) 调用此函数时,我收到以下错误:

SyntaxError: await is only valid in async function
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
⚠  Your function was killed because it raised an unhandled error.

相同的代码适用于其他 Firebase 项目

【问题讨论】:

  • Firebase Functions 默认在节点 v8 上运行,您的云运行的是什么版本?

标签: javascript firebase async-await google-cloud-functions


【解决方案1】:

您没有在问题中显示它,但包含对 await getRoomTempFromRoomId 的调用的函数本身未标记为 async。如果直接包含它的函数是 async 函数,则只能使用 await。并不是说 await 如果它在异步函数内部的匿名函数内部仍然不起作用,因为回调函数本身不是异步的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-18
    • 2020-09-07
    • 2019-09-12
    • 1970-01-01
    • 2020-12-23
    • 2020-08-13
    • 2020-04-15
    • 2019-06-14
    相关资源
    最近更新 更多