Skip to content

Instantly share code, notes, and snippets.

@jigewxy
Created April 23, 2018 02:29
Show Gist options
  • Save jigewxy/32ab057e4cd734c58cdc753359d62327 to your computer and use it in GitHub Desktop.
Save jigewxy/32ab057e4cd734c58cdc753359d62327 to your computer and use it in GitHub Desktop.
Async/Await
function sleep(ms){
return new Promise(function(resolve){
setTimeout(function(){
resolve('sleep for '+ ms + 'ms');
}, ms);
});
}
async function asyncFunction(){
console.time('asyncFunction total executing');
const sleep1 = await sleep(2000);
console.log('sleep 1:' + sleep1);
const[sleep2, sleep3, sleep4] = await Promise.all([sleep(2000), sleep(1000), sleep(1500)]);
console.log('sleep 2:' + sleep2);
console.log('sleep 3:' + sleep3);
console.log('sleep 4:' + sleep4);
const sleepRace = await Promise.race([sleep(3000), sleep(1000), sleep(500)]);
console.log('sleep race: ' + sleepRace);
console.timeEnd('asyncFunction total executing:');
return 'asyncFunction done';
}
asyncFunction().then(data=>{
console.log(data);
}).catch(error=>{
console.log(error);
});
console.log('after asyncFunction code executing....');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment