嵌套多个 then 函数是不好的做法吗?说“执行这个函数,当它完成后,执行这个函数”(等等)似乎很合乎逻辑,但代码看起来很糟糕。
如果有帮助,我最初是在 firestore 获取用户详细信息然后获取文档的上下文中进行此查询
firebaseApp.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
//If error
}).then(()=>{
firebaseApp.firestore().collection(collectionName).where("associatedID", "==", authID).get().then((snapshot)=>{
snapshot.docs.forEach(doc => {
//Do stuff with data that we've just grabbed
})
}).then(()=>{
//Tell the user in the UI
});
});
有其他选择吗?脑海里浮现的是这样的
var functionOne = () =>{
console.log("I get called later");
}
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 3000);
});
promise1.then(function(value) {
functionOne();
});
但即便如此,经过几次 .then() 之后它似乎也会变得复杂
最佳答案
从第一个外部 .then
返回 Promise,然后在第二个外部 .then
中使用 resolve 值,没有任何嵌套的 .then
s:
firebaseApp.auth().signInWithEmailAndPassword(email, password)
.then(()=>{
return firebaseApp.firestore().collection(collectionName).where("associatedID", "==", authID).get()
})
.then((snapshot) => {
snapshot.docs.forEach(doc => {
//Do stuff with data that we've just grabbed
});
//Tell the user in the UI
})
.catch((error) => {
// handle errors
});
确保不要过早catch
- 如果链中的任何地方出现错误,通常您会希望停止正常执行并直接转到末尾(例如,告诉用户那里是一个错误)。
如果您担心代码的可读性,请考虑使用 async
/await
(并为旧版浏览器转译您的生产代码):
// in an async function:
try {
await firebaseApp.auth().signInWithEmailAndPassword(email, password);
const snapshot = await firebaseApp.firestore().collection(collectionName).where("associatedID", "==", authID).get()
snapshot.docs.forEach(doc => {
//Do stuff with data that we've just grabbed
});
//Tell the user in the UI
} catch(error) {
// handle errors
}
关于javascript - 嵌套 .then() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57073684/