Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using axios with async and await

I am new in Async and await ecosystem, but I know that it gives the way of coding in a synchronous way (although it is async behind the scenes, just the way it is written in code).

So here is my code that I want to do in an async fashion.

const axios = require("axios");
async function getJSONAsync(){
  // The await keyword saves us from having to write a .then() block.
  let json = await axios.get('https://tutorialzine.com/misc/files/example.json');
  console.log('after the call to service');
  // The result of the GET request is available in the json variable.
  // We return it just like in a regular synchronous function.
  return json;
}

let abc = getJSONAsync();
console.log('>>>>>>>>>>> abc', abc);

Now there are some of the queries that I am unable to crack, let us see the output first:

>>>>>>>>>>> abc Promise { <pending> }
after the call to service
  1. The line is after the call to service came after the execution. Why? What happened to the async-await behavior?

Please shed some views?

Thank in advance, and happy coding :).

like image 483
Ankur Verma Avatar asked Mar 25 '18 08:03

Ankur Verma


People also ask

Can you use Axios with async await?

Axios Request With Async/AwaitYou start by specifying the caller function as async . Then use the await keyword with the function call. Due to the await keyword, the asynchronous function pauses until the promise is resolved.

Why is Axios asynchronous?

Axios is a promise based HTTP client for the browser and Node. js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.

How do you use await with Axios in React?

Using Async/Await For a function to use await , we must wrap the function itself as an async function: An async function is different than a sync function in that an async function doesn't block the processing of the code below it.

Can you use Axios on the front end?

Axios is a popular HTTP client available as a JavaScript library with more than 22 million weekly downloads as of May 2022. We can make API calls with Axios from JavaScript applications irrespective of whether the JavaScript is running on the front-end like a browser or the server-side.


1 Answers

You either need to call getJSONAsync within another async function with await:

async function main() {
    let abc = await getJSONAsync();
    console.log(abc);
    // ...
}

 main();

or call it and wait for the returned promise to resolve (ie. with Promise.prototype.then)

like image 126
fardjad Avatar answered Sep 22 '22 09:09

fardjad