简体   繁体   English

在 firebase 中使用 async/await 时我必须使用吗?

[英]Do I have to use .then when using async/await in firebase

Just as the title says do I need to use.then when inside a async/await function.正如标题所说,我需要使用.then 在 async/await function 中时。 What's the efficient way between the two两者之间的有效方式是什么

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

or或者

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

  return personList ;
};

In general, it's not a good idea to combine async/await with then/catch chains on the same promise.一般来说,在同一个 promise 上将 async/await 与 then/catch 链结合起来并不是一个好主意。 The whole point of async/await is to allow for more readable code that doesn't involve nesting callbacks with then/catch. async/await 的全部意义在于允许不涉及使用 then/catch 嵌套回调的更具可读性的代码。

Your second option is much more idiomatic JavaScript.您的第二个选择是更惯用的 JavaScript。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从我的 firebase db 获取数据时,如何正确使用 async 和 await? - How do I properly use async and await when getting data from my firebase db? 如果我定义了一个异步 function 并在 body 中使用 await,那么在调用 function 时是否需要使用 await? - If I define an async function and use await in the body, do I need to use await when calling the function? 当测试的 function 没有使用 async/await 时,我可以在 Jest 中使用 async/await 吗? - Can I use async/await in Jest, when the tested function is not using async/await? 如何在 JavaScript 中使用异步/等待? - How do I use async/await in JavaScript? 我是否必须等待已经异步的useEffect中的异步函数? - Do I have to await an async function in useEffect that is already async? async / await链中的所有功能都必须使用async / await关键字吗? - Do all functions in an `async/await` chain have to use the `async/await` keyword? 我可以在Firebase数据库调用中使用异步等待吗? - Can I use async await with firebase database call? 在 Firebase Cloud Functions 中使用 async/await 时返回一个 Promise - Returning a promise when using async/await in Firebase Cloud Functions 为什么在使用async-await语法时我仍然需要等待while循环? - Why I still have to wait for while loop when using async-await syntax? 在 JavaScript 中,我/应该如何将 async/await 与 XMLHttpRequest 一起使用? - In JavaScript how do I/should I use async/await with XMLHttpRequest?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM