gpt4 book ai didi

javascript - .then 和 .catch 都在同一个代码块中执行

转载 作者:行者123 更新时间:2023-11-30 19:48:12 24 4
gpt4 key购买 nike

所以我尝试阻止 item 进入数组,如果它已经存在一次的话。基本上,该函数正在完成它的工作,不允许插入一个已经存在的项目。但是,我使用 .catch 和 else 放置的所有错误消息都显示在屏幕上,意味着 .then 和 .catch 都在执行,我不明白为什么......这是我的代码:

 function onBuy() {
const email = firebase.auth().currentUser.email;
const ref = firebase.firestore().collection('parties').doc(String(name)).collection('users').doc(String(email));
const ref2 = firebase.firestore().collection('users').doc(String(email));
ref.get()
.then((doc) => {
if (!doc.exists) {
ref2.get()
.then((doc2) => {
if (doc2.exists) {
ref.set({
firstname: doc2.data().firstname,
lastname: doc2.data().lastname,
phone: doc2.data().phone
}).then(
ref2.update({ parties: firebase.firestore.FieldValue.arrayUnion(name) }).then(
Actions.pop()))
.catch(Alert.alert('fail'));
}
}).catch(Alert.alert('fail'));
}
else {
Alert.alert('this user already bought a ticket');
}
})
.catch(Alert.alert('this user already bought a ticket'));
}

我试图搜索解决方案,但没有找到答案。提前致谢:)

最佳答案

你必须意识到 .then 将结果/错误传递给下一个 .then/catch。您没有指定回调到 .catch;您所做的只是在 .then 之后立即调用 Alert.alert()

所以你应该有

someAsyncOperation(params)
.then(function(result){
// Do something with the result
})
.catch(function(error){
// Handle error
});

另请注意,您所有的 .then 似乎都没有返回任何内容。

关于javascript - .then 和 .catch 都在同一个代码块中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54750120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com