1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
const createTimeoutPromise = (callback, timeMs) => { return new Promise((resolve) => { setTimeout(() => { resolve(callback()); }, timeMs); }); }; const func2 = async () => { await createTimeoutPromise(() => { console.log(1); }, 300); await createTimeoutPromise(() => { console.log(2); }, 200); await createTimeoutPromise(() => { console.log(3); }, 100); }; const func3 = () => { const promises = []; promises.push( createTimeoutPromise(() => { // console.log(1); return 1; }, 300) ); promises.push( createTimeoutPromise(() => { // console.log(2); return 2; }, 200) ); promises.push( createTimeoutPromise(() => { // console.log(3); return 3; }, 100) ); return Promise.all(promises).then((results) => { results.forEach((result) => console.log(result)); }); }; const measureMs = async (func) => { const startTime = Date.now(); await func(); const endTime = Date.now(); const lapseMs = endTime - startTime; return lapseMs; }; const main = async () => { console.log('lapseMsFunc2: ' + (await measureMs(func2))); console.log('lapseMsFunc3: ' + (await measureMs(func3))); }; main(); |
1 2 3 4 5 6 7 8 |
1 2 3 lapseMsFunc2: 605 1 2 3 lapseMsFunc3: 300 |