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
- 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 :).
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
)
When you encounter an async call, the control of your program is returned to the calling method, until the async call completes.
So in your case, you call your async method, it sends and async request to get the resource and returns to the previous (on the callstack) method.
In that methos, you then try to log abc, which, at that point in time, is still getting the resource, so you just print a pending promise.
When the async call finally finishes, control is given back to your getJSONAsync () method and the console log there prints the message
Ok, after going a bit more inside the async-await magic I found that it would be better, if you are just trying some stuff to check, in this manner:
const axios = require("axios");
async function getJSONAsync(){
let json = await axios.get('https://tutorialzine.com/misc/files/example.json');
console.log('after the call to service');
return json;
}
(async()=>{
let abc = await getJSONAsync();
console.log('>>>>>>>>>>> abc', abc);
})();
Here I have created an async anonymous function that is being called just after its creation. Please let me know in case anyone has any doubt.
You bind async function result to variable and then log the variable, which at the time is unresolved Promise. When you get response from your request, second console.log appears.
To answer your question, the async/await behaviour is applied only inside async function, not in other parts of code that call this function etc.