Skip to content

Instantly share code, notes, and snippets.

@pozil
Created June 15, 2020 18:35
Show Gist options
  • Save pozil/0b610ee51c3871fdc59d31c2ab6b1250 to your computer and use it in GitHub Desktop.
Save pozil/0b610ee51c3871fdc59d31c2ab6b1250 to your computer and use it in GitHub Desktop.
Asynchronous JavaScript Cheatsheet
function callbackExample() {
setTimeout(_callback, 1000);
console.log('This appears instantaneously');
}
function promiseExample() {
_longRunningOperation()
.then(() => {
console.log('This appears later');
})
.catch((err) => {
console.error(`Error: ${err}`);
});
console.log('This appears instantaneously');
}
async function asyncAwaitExample() {
try {
await _longRunningOperation();
} catch (error) {
console.error(`Error: ${err}`);
}
console.log('This appears later');
}
function _callback() {
console.log('This appears later');
}
function _longRunningOperation() {
return new Promise((resolve, reject) => {
// Do something that takes time
const itWorked = true;
if (itWorked) {
resolve();
} else {
reject('something went wrong');
}
});
}
function pseudoParallelPromises() {
Promise.all([
_getTask('Task 1', 1500),
_getTask('Task 2', 500),
_getTask('Task 3', 1000)
]).then(() => {
console.log('All done');
});
// Ouput:
// Task 2 completed
// Task 3 completed
// Task 1 completed
// All done
}
function sequentialPromises() {
_getTask('Task 1', 1500)
.then(() => { return _getTask('Task 2', 500); })
.then(() => { return _getTask('Task 3', 1000); })
.then(() => {
console.log('All done');
});
// Ouput:
// Task 1 completed
// Task 2 completed
// Task 3 completed
// All done
}
async function sequentialAsyncAwait() {
await _getTask('Task 1', 1500);
await _getTask('Task 2', 500);
await _getTask('Task 3', 1000);
console.log('All done');
// Ouput:
// Task 1 completed
// Task 2 completed
// Task 3 completed
// All done
}
function _getTask(taskName, taskDuration) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`${taskName} completed`);
resolve();
}, taskDuration);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment