node.js - 如何等待从 Cloud Firestore 中获取数据,然后在 NodeJS 中返回它们?
问题描述
我想从 Cloud Firestore 中获取一些数据,然后在地图中返回该数据。问题是系统在获取该值之前返回该值并且承诺处于未决状态。我尝试了很多东西,但无法解决问题。如果有人可以帮助我,那就太好了!
function homepage(formData) {
var cfire = cfirebase.firestore().collection('Details').doc('dsadsadasdsadasdsdsdasd');
const test = cfire.get().then(doc => {
if (doc.exists) {
Name = doc.data().dd.dn;
vehical = doc.data().dd.vn;
vehicalNumber = doc.data().dd.vno;
console.log(Name, vehical, vehicalNumber);
} else if (!doc.exists) {
console.log("Detail does not exist");
return Promise.reject(new Error('Detail does not exist'));
} else {
throw Promise.reject(new Error('Server error!'));
}
}).catch(e => {
return false
});
return {
tripID: {
c: false,
dd: {
// Driver name
dn: Name,
// Vehical name
vn: vehical,
// Vehical number
vno: vehicalNumber,
}
}
};
}
解决方案
The reason why your function returns the object before you fetch data from cloud firestore is because cfirebase.firestore().collection(...).doc(...)
is asynchronous and it returns a Promise
, so you have to wait for that Promise
to resolve before you return the final object.
You should read up on asynchronous programming
if you're not familiar with the concept:
I suggest you change your homepage
function so that it returns a Promise
or utilize async/await
to wait for cfire.get()
to resolve with some value before you return
the final object.
Option #1
function homepage(formData) {
const cfire = cfirebase.firestore().collection(...).doc(...)
return cfire.get()
.then(doc => {
if (!doc) {
throw new Error("Server error")
}
if (!doc.exists) {
throw new Error("Details does not exist")
}
// ...
return { Name, vehical, vehicalNumber }
})
.then(result => {
// result => { Name, vehical, vehicalNumber }
// ...
return {
tripId: {...}
}
})
}
// then
homepage(...)
.then(result => {...})
.catch(error => {...})
Option #2
To use async/await
, you have to have Node.js 8.x
or higher.
async function homepage(formData) {
try {
const cfire = cfirebase.firestore().collection(...).doc(...)
const doc = await cfire.get()
if (!doc) {
throw new Error("Server error")
}
if (!doc.exists) {
throw new Error("Details does not exist")
}
// ...
return {
tripID: {...}
}
} catch(error) {
throw error
}
}
// then
homepage(...)
.then(result => {...})
.catch(error => {...})
Read more about async/await
:
Hope this helps.
推荐阅读
- postgresql - Postgres 约束:标志为 true 的行必须在 false 之前存在
- mongodb - 如何指示 MongoDB 子文档应该是数组而不是对象
- node.js - Node + socket.io + Typescript 无法正常工作
- r - 插补后操作动物园对象列
- c# - 我打开一个旧的 ASP.NET 项目后发现错误“'/'应用程序中的服务器错误”是什么原因。
- ionic-framework - 页面更改后传单 .bindPopup() 不起作用
- c# - 使用 FindControl 在运行时更改按钮文本
- python - 当字符串更改时,如何在不同的数据框中写入初始日期和最终日期?
- css - CSS媒体智能手机
- c# - Expression.Convert() 对于 EF Core 中的日期时间数据类型无法正常工作