JS Async Await - MacKittipat/note-developer GitHub Wiki
Reference
- https://medium.com/javascript-in-plain-english/async-await-javascript-5038668ec6eb
- https://medium.com/front-end-weekly/callbacks-promises-and-async-await-ad4756e01d90
- https://alligator.io/js/async-functions/
- https://www.loginradius.com/blog/async/callback-vs-promises-vs-async-await/
Sample code
function getmessage() {
console.log(new Date().toUTCString() + '>>> 4');
return new Promise(resolve => {
setTimeout(() => {
console.log(new Date().toUTCString() + '>>> 5');
resolve('Hello');
}, 3000);
});
}
// Using async simply implies that a promise will be returned,
// and if a promise is not returned, JavaScript automatically wraps it in a resolved promise with its value.
async function printMessage() {
console.log(new Date().toUTCString() + '>>> 3');
// await can be use inside async function only.
// The code will pause here until promise is returned.
let result = await getmessage();
console.log(new Date().toUTCString() + '>>> ' + result);
}
console.log(new Date().toUTCString() + ' >>> 1');
printMessage();
console.log(new Date().toUTCString() + '>>> 2'); // This line will not be blocked.
Output :
Sun, 19 Apr 2020 03:29:00 GMT >>> 1
Sun, 19 Apr 2020 03:29:00 GMT>>> 3
Sun, 19 Apr 2020 03:29:00 GMT>>> 4
Sun, 19 Apr 2020 03:29:00 GMT>>> 2
Sun, 19 Apr 2020 03:29:03 GMT>>> 5
Sun, 19 Apr 2020 03:29:03 GMT>>> Hello