Skip to content

Instantly share code, notes, and snippets.

@mugyu
Created April 27, 2019 02:41
Show Gist options
  • Save mugyu/1089804ecb185d2526c5b4a654c10137 to your computer and use it in GitHub Desktop.
Save mugyu/1089804ecb185d2526c5b4a654c10137 to your computer and use it in GitHub Desktop.
sample async/await
// these are samples for async/await
async function rejecting() {
throw "reject!!!!";
}
async function resolving(msg) {
await sleep(Math.random() * 10000);
return message = "resolve!" + (msg ? " -- " + msg : "");
}
resolving()
.then( value => {
console.log("==> ok");
console.log(value);
})
.catch( error => {
console.log("==> Oops!");
console.log(error);
});
rejecting()
.then( value => {
console.log("==> ok");
console.log(value);
})
.catch( error => {
console.log("==> Oops!");
console.log(error);
});
for (let i = 1; i < 10; i++) {
resolving(i).then(message => console.log(message))
}
// JavaScript simple sleep function
// usage: await sleep(milliseconds)
function sleep(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
// ==> Oops!
// reject!!!!
// resolve! -- 9
// resolve! -- 1
// resolve! -- 5
// resolve! -- 8
// resolve! -- 7
// ==> ok
// resolve!
// resolve! -- 2
// resolve! -- 3
// resolve! -- 6
// resolve! -- 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment