javascript - 嵌套 .then() 函数

标签 javascript ecmascript-6 es6-promise

嵌套多个 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 值,没有任何嵌套的 .thens:

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/

相关文章:

javascript - 如何使用 OnClick 事件调用 JS 函数

javascript - 在 Javascript 中嵌套许多函数调用(Unix 管道)的好方法

javascript - 将嵌套 Promise 中的 catch block 放入内部以触发外部 Promise 的 catch block ,是否有其他更清洁的方法?

javascript - 如何遍历数组/将数组映射到返回包含另一个 promise 的 promise 的函数

javascript - 从 $.ajax 调用返回一个 Javascript Promise

javascript - 影子 DOM 不显示内容。如何使内容在 DOM 中可见?

JavaScript 计算器 if 语句

javascript - 错误 : File to import not found or unreadable: ~bootstrap/scss/bootstrap

javascript - 如何分配给闭包内外部嵌套哈希中的键

javascript - 导出/导入语句中使用和不使用大括号符号有什么区别?