Skip to content

Instantly share code, notes, and snippets.

@andrelandgraf
Last active July 29, 2018 15:50
Show Gist options
  • Save andrelandgraf/abbfa1288011a00458299ce7c3d35ab8 to your computer and use it in GitHub Desktop.
Save andrelandgraf/abbfa1288011a00458299ce7c3d35ab8 to your computer and use it in GitHub Desktop.
working with async await
/**
* implementing return value of setTimeout() from callback to promise
* @param ms
* @returns {Promise<function>}
*/
const sleep = function (ms) {
// 4.) task 1: we create a new promise and call setTimeout(),
// set timeout creates a new taks 2 that will run after taks 1 has finished & 1500 milliseconds have passed
// new Promise(function(resolve, reject) { ... });
return new Promise(resolve => {
// 6.) task 2: as task 1 has stopped, the event loop goes on with task 2 after 1500 milliseconds have passed,
// we console.log('2');
setTimeout(() => {console.log('2'); resolve();}, ms);
});
};
async function allowAwait(){
// 2.) taks 1: async functions always return a promise, meaning that we can use await inside
// the function to 'wait' for some async taks
console.log('1');
// 3.) task 1: we console.log('1'); and now call sleep(1500)
// 5.) task 1: we come back from the sleep(1500) function call and hit await
// and will now stop task 1 (we are not blocking, we just give back to the event loop) to await task 2
await sleep(1500);
// 7.) task 1: after task has finished, task 1 continues and executes console.log('3');
console.log('3');
}
// 1.) task 1: we start here
allowAwait();
/* => Output:
* 1
* 2
* 3
* Working with promises does not only allow us to chain work with then() but also to await the promise directly.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment