Javascript 不等待异步 Firebase 实时数据库集函数
Javascript not waiting on async Firebase Realtime Database Set function
尽管我认为我掌握了异步函数在 JS 中的工作原理,但这个等待不正确。
外部函数,处理社交媒体,如按钮按下:
if (!postLiked){
likePost (uid, cardData)
.then (getPostLiked(uid))
.catch (error => console.log (error))
}
现在 likePost 函数,更新 firebase 实时数据库上的数据:
export function likePost(uid, cardData) {
return new Promise((resolve, reject) => {
//do stuff with the data...
set(ref(db, `${cardData.path}/likeData`), {
likeUids: newLikeUids,
likeCount: newLikeCount
})
.then (() => resolve ("DB: Uid like entry modified"))
.catch (error => reject (error))
})
}
预期行为:post 首先被点赞,然后更新 post 的点赞状态,表示点赞成功。
显示的行为:getpostLiked 函数不等待 likePost 执行,不更新 like 状态。
请帮我找出错误...在其他情况下,在set
之后使用then
表达式一直很有效...
非常感谢!
问题是
likePost(uid, cardData)
.then(getPostLiked(uid))
这基本上等同于
const result = getPostLiked(uid);
likePost(uid, cardData)
.then(result)
您正在立即调用 getPostLiked
而不是仅在 likePost
承诺解决时才调用它。将其更改为
.then(() => getPostLiked(uid))
避免显式 Promise 构造反模式也是一个好主意 - 因为 set
已经 returns 一个 Promise,所以没有必要围绕它构造另一个。
export function likePost(uid, cardData) {
return set(ref(db, `${cardData.path}/likeData`), {
likeUids: newLikeUids,
likeCount: newLikeCount
});
}
如果 Promise 构造函数的目的是更改解析值,则在 set
之后使用 .then
来执行此操作,而不是包装在另一个 Promise 中。
export function likePost(uid, cardData) {
return set(ref(db, `${cardData.path}/likeData`), {
likeUids: newLikeUids,
likeCount: newLikeCount
})
.then(() => "DB: Uid like entry modified");
}
尽管我认为我掌握了异步函数在 JS 中的工作原理,但这个等待不正确。 外部函数,处理社交媒体,如按钮按下:
if (!postLiked){
likePost (uid, cardData)
.then (getPostLiked(uid))
.catch (error => console.log (error))
}
现在 likePost 函数,更新 firebase 实时数据库上的数据:
export function likePost(uid, cardData) {
return new Promise((resolve, reject) => {
//do stuff with the data...
set(ref(db, `${cardData.path}/likeData`), {
likeUids: newLikeUids,
likeCount: newLikeCount
})
.then (() => resolve ("DB: Uid like entry modified"))
.catch (error => reject (error))
})
}
预期行为:post 首先被点赞,然后更新 post 的点赞状态,表示点赞成功。 显示的行为:getpostLiked 函数不等待 likePost 执行,不更新 like 状态。
请帮我找出错误...在其他情况下,在set
之后使用then
表达式一直很有效...
非常感谢!
问题是
likePost(uid, cardData)
.then(getPostLiked(uid))
这基本上等同于
const result = getPostLiked(uid);
likePost(uid, cardData)
.then(result)
您正在立即调用 getPostLiked
而不是仅在 likePost
承诺解决时才调用它。将其更改为
.then(() => getPostLiked(uid))
避免显式 Promise 构造反模式也是一个好主意 - 因为 set
已经 returns 一个 Promise,所以没有必要围绕它构造另一个。
export function likePost(uid, cardData) {
return set(ref(db, `${cardData.path}/likeData`), {
likeUids: newLikeUids,
likeCount: newLikeCount
});
}
如果 Promise 构造函数的目的是更改解析值,则在 set
之后使用 .then
来执行此操作,而不是包装在另一个 Promise 中。
export function likePost(uid, cardData) {
return set(ref(db, `${cardData.path}/likeData`), {
likeUids: newLikeUids,
likeCount: newLikeCount
})
.then(() => "DB: Uid like entry modified");
}