NodeJs等待仅在异步函数中有效



我正试图使用这个节点js代码在firestore中设置一些数据:

const db = admin.firestore();
const allDB = db.collection("like").doc("all").collection("movies");
const s1 = db.collection("like").doc("all");
await s1.set({
type: ["all"],
});

在控制台中运行文件:node file.js

给我这个错误:

await s1.set({
^^^^^
SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:1053:16)
at Module._compile (internal/modules/cjs/loader.js:1101:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47

如何解决这个问题

用异步函数包装代码

async function run(){
const db = admin.firestore();
const allDB = db.collection("like").doc("all").collection("movies");
const s1 = db.collection("like").doc("all");
await s1.set({
type: ["all"],
});
}
run().catch(e => { console.error(e); process.exit(-1); })

您应该在异步函数中使用它,这将起作用:

const doSomething = async () => {
const db = admin.firestore();
const allDB = db.collection("like").doc("all").collection("movies");
const s1 = db.collection("like").doc("all");
await s1.set({
type: ["all"],
});
}

就像上面的答案一样,你只需要使用async标题来创建一个异步函数,然后用里面的东西命名一个函数

最新更新