Save Async/Await response on a variable

后端 未结 5 2090
误落风尘
误落风尘 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:54

    try..catch creates a new block scope. Use let to define data before try..catch instead of const, return data from asyncExample function call

    (async() => {
    
      const users = 123;
    
      const asyncExample = async() => {
        let data;
        try {
          data = await Promise.resolve(users);
        } catch (err) {
          console.log(err);
        }
        return data;
      };
    
      //Save response on a variable
      const globalData = await asyncExample();
      console.log(globalData);
      // return globalData;
    })();

提交回复
热议问题