Save Async/Await response on a variable

后端 未结 5 2068
误落风尘
误落风尘 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 13:19

    I had same issue with you and found this post. After 2 days of trying I finally found a simple solution.
    According to the document of JS, an async function will only return a Promise object instead of value. To access the response of Promise, you have to use .then()method or await which can return the resulting object of Promise is instead of Promise itself.
    To change variables from await, you have access and change the variable you want to assign within the async function instead of return from it.

    //Save response on a variable
    var globalData;
    const asyncExample = async () =>{
        try {
            const data = await axios(users);
            globalData = data; // this will change globalData
            console.log(data); //200
        }
        catch (err) {
            console.log(err);
        }
    };
    asyncExample();
    

    But if you do this, you may get an undefined output.

    asyncExample();
    console.log(globalData) //undefined
    

    Since asyncExample() is an async function, when console.log is called, asyncExample() has not finished yet, so globalData is still not assigned. The following code will call console.log after asyncExample() was done.

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

提交回复
热议问题