(reference : https://tutorialzine.com/2017/07/javascript-async-await-explained)
-
Automatically transforms a regular function into a Promise.
-
When called async functions resolve with whatever is returned in their body.
-
Async functions enable the use of await.
-
When placed in front of a Promise call, await forces the rest of the code to wait until that Promise finishes and returns a result.
-
Await works only with Promises, it does not work with callbacks.
-
Await can only be used inside async functions.
function getJSON(){
// To make the function blocking we manually create a Promise.
return new Promise( function(resolve) {
axios.get('https://tutorialzine.com/misc/files/example.json')
.then( function(json) {
// The data from the request is available in a .then block
// We return the result using resolve.
resolve(json);
});
});
}
// Async/Await approach
// The async keyword will automatically create a new Promise and return it.
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');
// The result of the GET request is available in the json variable.
// We return it just like in a regular synchronous function.
return json;
}```