Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - Save Async/Await response on a variable

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> }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...