Save Async/Await response on a variable

落花浮王杯 提交于 2020-06-24 04:50:11

问题


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 throughout the rest of the code?

const axios = require('axios');
const users = 'http://localhost:3000/users';

const asyncExample = async () =>{
    try {
        const data = await axios(users);
        console.log(data); //200
    }
    catch (err) {
        console.log(err);
    }
};

//Save response on a variable
const globalData = asyncExample(); 
console.log(globalData) //Promise { <pending> }

回答1:


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()



回答2:


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



回答3:


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



回答4:


Because the events are happening asynchronously you need to tie in a callback/promise. I'm going to assume it returns a promise.

const axios = require('axios');
const users = 'http://localhost:3000/users';

const asyncExample = async () =>{
    try {
        const data = await axios(users);
        console.log(data); //200
    }
    catch (err) {
        console.log(err);
    }
};

//Save response on a variable
const globalData = asyncExample().then( (success, err) => {
  if (err) { console.error(err); }
  console.log(success)
}



回答5:


Just use a callback/promise (cascading programming):

axios(users).then(function(response) {
    const globalData = response;
    console.log(globalData) 
});


来源:https://stackoverflow.com/questions/48327559/save-async-await-response-on-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!