【问题标题】:Firestore takes a long time to end execution after executingFirestore 执行后需要很长时间才能结束执行
【发布时间】:2021-02-12 15:12:31
【问题描述】:

我有一个非常简单的 Firestore 应用。除了设置firebase.initializeApp(firebaseConfig);之外,就只有这个了:

db.collection("users").add({
    username: username
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});

然而,当我使用node index.js 运行此应用程序时,它会写入Document written with ID: XYZ,然后需要一分钟才能结束并将控制权交还给终端。我可能在这里没有使用精确的术语,因此也将不胜感激。

这是有原因的吗?我应该终止连接还是什么?

【问题讨论】:

  • 您可以将process.exit() 放入.then() 处理程序中。
  • Firestore 似乎有一个 .terminate() 方法来关闭所有打开的流。还有一个 .waitForPendingWrites() 方法返回一个承诺,我不知道你是否必须在调用 .terminate() 之前先调用它(并等待完成),或者 .terminate() 是否为你处理。
  • 此处Why is my nodejs script waiting 60 seconds before terminating 进行了类似的讨论,尽管它的建议与使用.terminate() 不同。但显然,有一些内部 Firestore 计时器会导致 60 秒问题。我不确定这个答案是否比使用.terminate() 更好。
  • 所以它实际上是一个 Firebase 的东西。感谢您的帮助!

标签: javascript node.js firebase google-cloud-firestore


【解决方案1】:

这是一个简单的应用程序,所以它可能不适合你。

承诺版本:

如果你想保留我在问题中提出的结构,那么这是最终版本

db.collection("users").add({
    username: "John"
})
.then( (docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch( (error) => {
    console.error("Error adding document: ", error);
})
.then( () => {
    console.log("Done");
    db.terminate();
})

异步等待版本:

但我不喜欢.then().catch(),所以我决定将其转换为匿名自执行异步函数。如果你不想,你显然不需要让它自动执行或匿名。

(async () => {
    try {
        const docRef = await db.collection("users").add({
            username: "John"
        });
        console.log("Document written with ID: ", docRef.id);
    } catch (error) {
        console.error("Error adding document: ", error);
    } finally {
        console.log("Done");
        db.terminate();
    }
})();

在这个特定的用例中,它可能看起来并不简单,但我认为使用 async await 可以使函数顺序化并且更易于阅读。

【讨论】:

    猜你喜欢
    • 2012-12-03
    • 2011-03-14
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    相关资源
    最近更新 更多