Skip to content

Instantly share code, notes, and snippets.

@Zantier
Last active July 4, 2019 16:25
Show Gist options
  • Save Zantier/63e4b29b74e44aed4b270cd84966a713 to your computer and use it in GitHub Desktop.
Save Zantier/63e4b29b74e44aed4b270cd84966a713 to your computer and use it in GitHub Desktop.
javascript async/await vs Promise
// Both these pieces of code produce the same output, but the async method is neater, because
// all the variables stay in scope, and we can use a return statement to end the execution
// at any point.
// Here is the output in both cases:
// f has been called with param 2
// ...
// The quotient is 5
// f has been called with param -1
// Dividing by 1 is not interesting
// f has been called with param -2
// Error: Attempt to divide by 0
// at f (index.js:...)
// async
// -----
const sleep = async (ms) => new Promise(resolve => setTimeout(resolve, ms));
const getDivisor = async (offset) => 2 + offset;
const f = async (param) => {
console.log(`f has been called with param ${param}`);
try {
const divisor = await getDivisor(param);
if (divisor === 0) {
throw new Error('Attempt to divide by 0');
}
if (divisor === 1) {
console.log('Dividing by 1 is not interesting');
return;
}
console.log('...');
await sleep(1000);
const quotient = 20 / divisor;
console.log(`The quotient is ${quotient}`);
} catch (err) {
console.log(err);
}
}
(async () => {
await f(2);
await f(-1);
f(-2);
})();
// promise
// -------
const sleep = async (ms) => new Promise(resolve => setTimeout(resolve, ms));
const getDivisor = async (offset) => 2 + offset;
const f = (param) => {
console.log(`f has been called with param ${param}`);
return getDivisor(param).then(divisor => {
if (divisor === 0) {
throw new Error('Attempt to divide by 0');
}
if (divisor === 1) {
console.log('Dividing by 1 is not interesting');
return;
}
console.log('...');
return sleep(1000).then(() => divisor);
}).then(divisor => {
if (divisor === undefined) {
return;
}
const quotient = 20 / divisor;
console.log(`The quotient is ${quotient}`);
}).catch(err => {
console.log(err);
});
}
(async () => {
await f(2);
await f(-1);
f(-2);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment