async javascript
(async () => {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
...
})();
async javascript
(async () => {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
...
})();
async and await
function delayResult() {
return new Promise(resolve => {
setTimeout(() => {
resolve(‘Done’);
}, 5000)
})
}
async function getResult() {
let result = await delayResult();
return result;
}
getResult();
javscript async await explained
// Promise approach
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;
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us