/* * * * * * * * * * * * * * * * * * * UTILITIES */ function resolveAfter2Seconds() { return new Promise(resolve => { setTimeout(() => { resolve(spent_time(ori_date) + 'lente'); }, 2000); }); } function resolveAfter1Seconds() { return new Promise(resolve => { setTimeout(() => { resolve(spent_time(ori_date) + 'rapide'); }, 1000); }); } function print_time(my_date = new Date) { let my_time = my_date.getSeconds(); my_time += ":"; my_time += my_date.getMilliseconds(); return '[' + my_time + '] '; } function spent_time(ori_date) { let my_date = new Date(); let my_seconds = my_date.getSeconds() - ori_date.getSeconds(); if (my_seconds < 0 ) my_seconds += 60; let my_millis = my_date.getMilliseconds() - ori_date.getMilliseconds(); if (my_millis < 0 ) my_millis += 1000; return '[' + my_seconds + ':' + my_millis + '] '; } /* * * * * * * * * * * * * * * * * * * TESTS /* async function asyncCall() { console.log(spent_time(ori_date) + 'calling'); const lente = await resolveAfter2Seconds(); const rpide = await resolveAfter1Seconds(); console.log(spent_time(ori_date) + lente); console.log(spent_time(ori_date) + rpide); } // "[0:1] calling" // "[0:4] after" // "[3:6] [2:4] lente" // "[3:15] [3:6] rapide" */ /* function asyncCall() { console.log(spent_time(ori_date) + 'calling'); const lente = resolveAfter2Seconds(); const rpide = resolveAfter1Seconds(); console.log(spent_time(ori_date) + lente); console.log(spent_time(ori_date) + rpide); } // "[0:1] calling" // "[0:4] [object Promise]" // "[0:12] [object Promise]" // "[0:19] after" */ /* function asyncCall() { console.log(spent_time(ori_date) + 'calling'); resolveAfter2Seconds().then(message => console.log(spent_time(ori_date) + message)) .then(() => resolveAfter1Seconds()).then(message => console.log(spent_time(ori_date) + message)); } // "[0:1] calling" // "[0:4] after" // "[2:4] [2:4] lente" // "[3:15] [3:15] rapide" */ /* async function asyncCall() { console.log(spent_time(ori_date) + 'calling'); const lente = await resolveAfter2Seconds(); console.log(spent_time(ori_date) + 'middle'); const rpide = await resolveAfter1Seconds(); console.log(spent_time(ori_date) + lente); console.log(spent_time(ori_date) + rpide); } // "[0:1] calling" // "[0:2] after" // "[2:4] middle" // "[3:7] [2:4] lente" // "[3:8] [3:6] rapide" */ async function asyncCall() { console.log(spent_time(ori_date) + 'calling'); const lente = resolveAfter2Seconds(); const rpide = resolveAfter1Seconds(); console.log(spent_time(ori_date) + await lente); console.log(spent_time(ori_date) + await rpide); } // "[0:0] calling" // "[0:3] after" // "[0:3] [2:4] lente" // "[2:5] [1:3] rapide" /* * * * * * * * * * * * * * * * * * * LAUNCH TEST */ let ori_date = new Date(); asyncCall(); console.log(spent_time(ori_date) + "after");