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
Please shed some views?
Thank in advance, and happy coding :).
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.
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.
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.
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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With