Skip to content

Instantly share code, notes, and snippets.

@CrashedBboy
Last active January 19, 2019 01:41
Show Gist options
  • Save CrashedBboy/fa06503c895c1adb1f7930791ee3f5ab to your computer and use it in GitHub Desktop.
Save CrashedBboy/fa06503c895c1adb1f7930791ee3f5ab to your computer and use it in GitHub Desktop.
Learning await/async in Javascript
async function start () {
try {
let result1 = await callAwaitFunction(2);
console.log(result1);
let result2 = await callAwaitFunction(-1);
console.log(result2);
// these 2 lines won't be reached because of the exception
let result3 = await callAwaitFunction(2);
console.log(result3);
} catch (e) {
console.log('err: ', e);
}
}
async function callAwaitFunction(number) {
console.log('call callAwaitFunction('+ number +')');
return new Promise(function(resolve, reject) {
setTimeout(function() {
if (number >= 0) {
resolve('It\'s a positive.')
} else {
reject('It\'s a negative.')
}
}, 1000)
})
}
// notice that we can't use await in a regular function or top level code,
// so we need to have a wrapping async function
start();
call callAwaitFunction(2)
It's a positive.
call callAwaitFunction(-1)
err: It's a negative.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment