繁体   English   中英

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

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

介绍

我是 javascript 承诺世界的新手,我需要了解它们如何正确工作......

直到知道我一直在我的代码中这样做:

  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
      });
  };

我不知道我是否在做反模式......但基本上我需要知道这是否是一个好方法以及我是否正确地这样做。

问题

  1. 我是否必须将 fetchUserData 函数声明为异步才能返回承诺?

  2. 我可以在 then/catch 正文中使用 async await 吗?

  3. 我可以这样做吗?

     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); };

如果有人指导我,我将不胜感激。 谢谢。

单词asyncawait只是thencatch语法糖。

这个:

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

相当于:

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

   return userData
 }

在这里你返回任何东西(成功或错误)。 如果你想处理这里的错误,只需放一个 try/catch 子句。

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

请注意,您只能在async函数中使用await子句。

1.
函数可以返回Promise而不会被声明为async ,只要你不在里面等待,

2.
你不应该在then使用async-await ,只需返回一个 Promise ,它会在接下来的then解决,

3.
使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM