Created
February 5, 2020 19:07
-
-
Save herrera-ignacio/2535be6683991855aa94178f390943cc to your computer and use it in GitHub Desktop.
Javascript async vs promise example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const asyncTask = (taskNumber) => new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log(`Async task-${taskNumber} done`); | |
resolve(); | |
}, Math.random() * 1000 * 3); | |
}); | |
const asyncJob = async () => { | |
console.log('Starting Async Job'); | |
await asyncTask(1); | |
console.log('Async job done'); | |
}; | |
const asyncJobPromisified = new Promise((resolve, reject) => { | |
console.log('Starting Async Job'); | |
asyncTask(1).then(() => { | |
console.log('Async job done'); | |
resolve(); | |
}); | |
}); | |
const workWithAsyncJob = async () => { | |
console.log('Starting sync work with ONE ASYNC job'); | |
// What would happen if you remove await? | |
await asyncJob(); | |
console.log('Finished sync work'); | |
}; | |
workWithAsyncJob().then(() => console.log('SUCCESS')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment