Skip to content

Instantly share code, notes, and snippets.

@guillefd
Forked from bmorelli25/async2.js
Last active January 30, 2019 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillefd/6adc6b23b3fb78868f650352f82ef81d to your computer and use it in GitHub Desktop.
Save guillefd/6adc6b23b3fb78868f650352f82ef81d to your computer and use it in GitHub Desktop.
Async/Await Example
/// EXAMPLE 1
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
console.log(result);
// expected output: 'resolved'
}
asyncCall();
//// EXAMPLE 2
function doubleAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x * 2);
}, 2000);
});
}
async function addAsync(x) {
const a = await doubleAfter2Seconds(10);
const b = await doubleAfter2Seconds(20);
const c = await doubleAfter2Seconds(30);
return x + a + b + c;
}
addAsync(10).then((sum) => {
console.log(sum);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment