【发布时间】:2016-11-25 11:21:40
【问题描述】:
我有一个在 Node.js 中运行的简单 Firebase 查询,它成功返回数据。但是,Node.js 应用程序没有完成。它挂起,好像它正在等待与 Firebase 相关的某些事情完成。实现这一点以便 Node.js 应用程序完成的正确方法是什么?
参考资料:
遵守我们的承诺(和回调) https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html
Node.js Firebase 查询 https://firebase.google.com/docs/reference/node/firebase.database.Query
代码:
调用我的exists方法以查看Firebase中是否存在产品url。
firebase.exists(url)
.then(data => console.log(data))
.catch(data => console.log(data));
检查产品网址是否存在于 Firebase 中的方法。返回一个承诺。请注意 Firebase once 方法的使用。
public exists(url): any {
return this.firebase.database().ref('products/').orderByChild("url").equalTo(url).once("value").then(function (snapshot) {
return snapshot.exists();
});
}
来自https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html的代码示例
// Fetch a Blog Post by ID. Returns a Promise of an actual object, not a DataSnapshot.
function getArticlePromise(id) {
return ref.child('blogposts').child(id).once('value').then(function(snapshot) {
return snapshot.val();
});
}
回答:通过使用下面 Frank 建议的 process.exit() 能够解决此问题。
firebase.exists(url)
.then(data => { console.log(data); process.exit(); })
.catch(data => console.log(data));
【问题讨论】:
标签: node.js firebase promise firebase-realtime-database