简体   繁体   English

Javascript 异步函数返回 then-catch 承诺?

[英]Javascript async function return then-catch promise?

Introduction介绍

I am new in the world of javascript promises and I need to understand how they work correctly...我是 javascript 承诺世界的新手,我需要了解它们如何正确工作......

Until know I have been doing this in my code:直到知道我一直在我的代码中这样做:

  const handleRefresh = () => {
    setIsRefreshing(true);

    fetchUserData()
      .then(async () => { <--------- Using then because I return a promise in fetchUserData
         await fetchUserPosts(); <------- Using await here
         setIsRefreshing(false);
      }).catch(err => { <--------- This will catch the error I have thrown in the function fetchUserPosts or inside the then body
       // TODO - Show error
       setIsRefreshing(false);
       console.log(err)
    );
  };

  const fetchUserData = async () => { <------ async function
    const { firebase } = props;

    const userId = firebase.getCurrentUser().uid;

    const documentRef = firebase.getDatabase().collection("users").doc(userId);

    // Fetch all the user information
    return documentRef <--------- Returning the promise here
      .get()
      .then((doc) => {
        if (doc.exists) {
          // Get all user data
          const data = doc.data();
          console.log(data);
          setUserData(data);
        }
      })
      .catch((err) => {
        throw err; <----------- Throwing error
      });
  };

I don't know if I am doing anti patterns... But basically I need to know if this is a good way and if I am doing this correctly.我不知道我是否在做反模式......但基本上我需要知道这是否是一个好方法以及我是否正确地这样做。

Questions问题

  1. Do I have to declare the fetchUserData function as async to return a promise?我是否必须将 fetchUserData 函数声明为异步才能返回承诺?

  2. Can I use the async await in the then/catch body?我可以在 then/catch 正文中使用 async await 吗?

  3. Can I do this?我可以这样做吗?

     const handleRefresh = async () => { setIsRefreshing(true); await fetchUserData() .then(async () => { <--------- Using then because I return a promise in fetchUserData await fetchUserPosts(); <------- Using await here }).catch(err => { <--------- This will catch the error I have thrown in the function fetchUserPosts or inside the then body // TODO - Show error console.log(err) ); setIsRefreshing(false); };

I would really appreciate if someone guides me.如果有人指导我,我将不胜感激。 Thanks.谢谢。

the words async and await are only syntactic sugar for then and catch .单词asyncawait只是thencatch语法糖。

This:这个:

  fetchUserData()
    .then(data => return data )
    .catch(error => return error)

is equivalent to:相当于:

 async function getUserData() {
   const userData = await fetchUserData()

   return userData
 }

Here you are returning anything (success or error).在这里你返回任何东西(成功或错误)。 If you want to treat the error here, just put a try/catch clause.如果你想处理这里的错误,只需放一个 try/catch 子句。

  async function getUserData() {
   try {
     return await fetchUserData()
   } catch (e) {
     return e.message
   }
 }

Note that you can only use the await clause within an async function.请注意,您只能在async函数中使用await子句。

1. 1.
Function can return Promise without being declared as async as long as you don't await inside it,函数可以返回Promise而不会被声明为async ,只要你不在里面等待,

2. 2.
You should not use async-await inside then , simply return a Promise and it'll be resolved in the following then ,你不应该在then使用async-await ,只需返回一个 Promise ,它会在接下来的then解决,

3. 3.
When using async-await syntax, Promises are awaited in a declarative way as demonstrated below:使用async-await语法时,Promise 以声明方式等待,如下所示:

const handleRefresh = async () => {
  try
  {
    const a = await getA()
    // pass the result to another Promise
    const b = await getB(a)
    const c = await getC(b)
  
  } catch (error)
  {
    handleError(error)
  } 
};

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

相关问题 如何在带有 jquery 请求到 google drive api 的函数中正确实现 async-await 或 then-catch - How to implement async-await or then-catch correctly in a function with jquery request to google drive api Javascript:在异步函数中返回一个promise - Javascript: Return a promise inside async function 如何从异步类函数 JavaScript 返回 Promise - How to return Promise from an async class function JavaScript 尽管Promise.resolve(),promise catch块中的Java代码重试异步功能始终运行 - Javascript retry async function in promise catch block always runs despite Promise.resolve() JavaScript异步函数,当没有返回值的情况下,返回时应答应解决 - JavaScript async function, when is returned promise resolved in the case of no return value 通过异步函数解决promise返回 - Resolve promise return by Async function 如何正确使用try / catch,promise catch和async功能? - How to use try/catch, promise catch and async function correctly? 如何在javascript中的异步等待中返回承诺? - How to return a promise inside the async await in javascript? Javascript - 异步等待和获取 - 返回值,而不是承诺? - Javascript - Async await and fetch - return the value, not the promise? 潜在的异步函数会返回一个立即解析的承诺吗? - Potentially async function return a promise that immediately resolves?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM