【发布时间】:2021-07-02 19:52:20
【问题描述】:
当我调用函数时,它将 [object Promise] 而不是数据,我认为 Promise 将处于挂起状态,然后返回。谁能帮助我以正确的方式做到这一点?
这是我的 util 函数。
export const GetDataFromSnapshot = async (snapshot) => {
const data = [];
try {
return await snapshot.onSnapshot((docs) => {
const currentState = [];
docs.forEach((doc) => {
currentState.push(doc.data());
});
data.push(currentState);
console.log(currentState);
// 0:
// id: "71u638UFCpGs6hLkWP"
// timestamp: t {seconds: 2177433000, nanoseconds: 0}
// title: "Remind Me in future"
});
} catch (error) {
console.log(error);
}
};
这个由 saga-watcher 生成器函数调用的函数看起来像这样。
// TODO: action calling the API
function* fetchReminder() {
try {
const reminders = yield call(GetAllReminders);
const resultDoc = GetDataFromSnapshot(reminders);
console.log(`resultDoc =>> ${resultDoc}`);
// resultDoc =>> [object Promise]
resultDoc
.then((data) => {
console.log(`resultDoc =>> ${resultDoc}`);
// resultDoc =>> [object Promise]
console.log(`data =>> ${data}`);
// data =>> function () {
// i.Zl(), r.cs.ws(function () {
// return Pr(r.q_, o);
// });
// }
data.json();
// Unhandled Rejection (TypeError): data.json is not a function
})
.then((response) => console.log(`response =>> ${response}`));
yield put(setReminder(reminders));
如何获取数据将如下所示。来自 firestore 数据库的对象数组
0:
id: "71u638UFCpGs6hLkWP"
timestamp: t {seconds: 2177433000, nanoseconds: 0}
title: "Remind Me in future"
【问题讨论】:
-
看看我的回答,应该可以帮到你:)
-
你的代码写得好像
snapshot.onSnapshot()返回一个promise,它解析为具有.json()方法的东西。这似乎不太可能,看起来更像是您刚刚复制粘贴了一些示例代码。在我看来data数组是你想从GetDataFromSnapshot()返回的东西,如果.onSnapshot()没有返回你需要自己promisify的承诺。 -
@Lennholm,你做得对,但是我自己如何承诺,你能帮我快速理解你所说的承诺和所有东西的代码或任何链接。
-
@Lennholm,你是对的
.onSnapshot()在此处正确返回[object Promise]。我又检查了一遍。但是我在这里没有得到.json()的值。
标签: javascript reactjs firebase firebase-realtime-database