-
-
Save guillefd/6adc6b23b3fb78868f650352f82ef81d to your computer and use it in GitHub Desktop.
Async/Await 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
/// 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