Skip to content

Instantly share code, notes, and snippets.

@diewland
Created August 4, 2017 03:53
Show Gist options
  • Select an option

  • Save diewland/540f6a593c323de46d104622b2a62ccb to your computer and use it in GitHub Desktop.

Select an option

Save diewland/540f6a593c323de46d104622b2a62ccb to your computer and use it in GitHub Desktop.
JavaScript async/await playground
// utility
function stamp_time(text){
console.log(new Date().toLocaleTimeString(), text);
}
// mock process
function make_double(v){
return new Promise(function(res, rej){
setTimeout(x => {
res(v*2); // double value
}, v*1000); // take v sec to process
}).then( out => {
stamp_time(`Job ${v} done`);
return out;
});
}
async function async_way(){
stamp_time(`Job start`);
/*
var a = await make_double(1); // +1 sec
var b = await make_double(2); // +2 sec
return a + b; // total 3 sec
*/
var a = make_double(1);
var b = make_double(2);
return await a + await b; // start a, b same time
// a done in 1 sec wait b
// b done in 2 sec
// total 2 sec
}
function promise_all_way(){
stamp_time(`Job start`);
var a = make_double(1);
var b = make_double(2);
return Promise.all([a, b]).then((o) => {
return o[0] + o[1];
});
}
// test
function test1(){
console.log(`===== async way =====`);
async_way().then(o => {
console.log('Output => ' + o);
}).then(x => {
console.log(`===== Promise.all way =====`);
promise_all_way().then(o => {
console.log('Output => ' + o);
console.log('===========================');
});
});
}
async function test2(){
console.log(`===== async way =====`);
var o = await async_way();
console.log('Output => ' + o);
//
console.log(`===== Promise.all way =====`);
var o = await promise_all_way();
console.log('Output => ' + o);
//
console.log('===========================');
}
// run test
// test1();
test2();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment