Last active
January 19, 2019 01:41
-
-
Save CrashedBboy/fa06503c895c1adb1f7930791ee3f5ab to your computer and use it in GitHub Desktop.
Learning await/async in Javascript
This file contains hidden or 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
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(); |
This file contains hidden or 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
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