首页 > 解决方案 > 在 Firebase 中使用 async/await 时,我是否必须使用 .then

问题描述

正如标题所说,我是否需要在 async/await 函数中使用 .then 。两者之间的有效方式是什么

setPersonList = async ()=> {
  const personList = [];
  await this.firestoreCollection
  .get()
  .then(result => {
    personList  = { ...result.data };
  });
  return personList ;
};

或者

setPersonList = async () => {
  const personList = [];
  const snapshot = await this.firestoreCollection
  .get()
  snapshot.docs.forEach((doc) => {
      personList .push(doc.data());
  });

  return personList ;
};

标签: javascriptfirebaseasync-await

解决方案


一般来说,将 async/await 与 then/catch 链结合在同一个 Promise 上并不是一个好主意。async/await 的全部意义在于允许不涉及使用 then/catch 嵌套回调的更具可读性的代码。

您的第二个选项是更惯用的 JavaScript。


推荐阅读