Save Async/Await response on a variable

后端 未结 5 2079
误落风尘
误落风尘 2020-12-24 12:47

I am trying to understand async calls using async/await and try/catch.

In the example below, how can I save my successful response to a variable that can be utilized

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 12:57

    1) Return something from your asyncExample function

    const asyncExample = async () => {
      const result = await axios(users)
    
      return result
    }
    

    2) Call that function and handle its returned Promise:

    ;(async () => {
      const users = await asyncExample()
      console.log(users)
    })()
    

    Here's why should you handle it like this:

    • You can't do top-level await (there's a proposal for it though); await must exist within an async function.

    However I must point out that your original example doesn't need async/await at all; Since axios already returns a Promise you can simply do:

    const asyncExample = () => {
      return axios(users)
    }
    
    const users = await asyncExample()
    

提交回复
热议问题