JavaScriptのPromise配列とPromise.all()の練習
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 |
const main = () => { const p = console.log const getTimeoutPromise = (func, arg, time_ms) => { return new Promise((resolve, reject) => { setTimeout(() => { func(arg) resolve(arg) }, time_ms) }) } const execPromises_getTimeLapse = (promises, funcForResults) => { const startTime_ms = new Date() Promise.all(promises).then(results => { funcForResults(results) const endTime_ms = new Date() const timelapse_ms = endTime_ms - startTime_ms p("timelapse_ms : " + timelapse_ms) }); } const sub = () => { const promises = [] promises.push(getTimeoutPromise(p, "timeout1", 7)) promises.push(getTimeoutPromise(p, "timeout2", 0)) promises.push(getTimeoutPromise(p, "timeout3", 54)) promises.push(getTimeoutPromise(p, "timeout4", 32)) promises.push(getTimeoutPromise(p, "timeout5", 2)) execPromises_getTimeLapse(promises, p) } sub() } main() |
1 2 3 4 5 6 7 |
timeout2 timeout5 timeout1 timeout4 timeout3 [ 'timeout1', 'timeout2', 'timeout3', 'timeout4', 'timeout5' ] timelapse_ms : 56 |