【发布时间】:2019-07-17 10:22:56
【问题描述】:
嵌套多个 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块中返回承诺,这样您只会获得一层嵌套 - javascript.info/promise-chaining -
...或者通过采用
async/await而不是直接处理Promise接口来完全回避这个问题。您的代码将立即变得更具可读性。如果这(由于某种原因)不可能,这篇文章应该很有用:medium.com/@pyrolistical/…
标签: javascript ecmascript-6 es6-promise