Skip to content

Instantly share code, notes, and snippets.

@herrera-ignacio
Created February 5, 2020 19:07
Show Gist options
  • Save herrera-ignacio/2535be6683991855aa94178f390943cc to your computer and use it in GitHub Desktop.
Save herrera-ignacio/2535be6683991855aa94178f390943cc to your computer and use it in GitHub Desktop.
Javascript async vs promise example
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