我有一个非常简单的 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
,然后又需要一分钟才能结束并将控制权交还给终端。我可能没有在这里使用准确的术语,因此也欢迎您进行更正。
这是有原因的吗?我应该终止连接还是什么?
答案 0 :(得分: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 可以使函数有序且更易于阅读。