NodeJs等待仅在异步功能中有效

时间:2020-09-24 18:34:07

标签: node.js google-cloud-firestore

我正在尝试使用此节点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

如何解决此问题

3 个答案:

答案 0 :(得分:2)

将代码包装在异步函数中

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); })

答案 1 :(得分:2)

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

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"],
  });
}

答案 2 :(得分:0)

就像上面的答案一样,您只需要使用async标题来创建一个异步函数,然后使用其中的内容命名一个函数即可