async await asynchronous sending request example

Here is a simple simulation. Use setTimeout to simulate sending requests.
When we get a back-end return information, we can write it like the following getUserInfo function.
That is, the request will be sent to the backend for the first time and stored in the userInfo variable. You can get it directly from userInfo when you get it later. The async function returns the value when the promise function resolves. But the async function cannot handle the reject value, so try catch is generally needed to get the reject return value.

let userInfo
    async function fetchUserInfo() {
    
    
      if (userInfo) {
    
    
        return await userInfo
      } else {
    
    
        return await new Promise((resolve, reject) => {
    
    
          setTimeout(() => {
    
    
            userInfo = {
    
     name: 'nihao' }
            reject(userInfo)
          }, 2000)
        })
      }
    }

    async function getUserInfo() {
    
    
      try {
    
    
        const info = await fetchUserInfo()
        return info
      } catch (error) {
    
    
        console.log('error', error)
      }
    }
    const info = getUserInfo()

Guess you like

Origin blog.csdn.net/qq_42535651/article/details/106613526