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 60 61 62 63 64 65 66
| var urls = [ { info: 'link1', time: 3000 }, { info: 'link2', time: 2000 }, { info: 'link3', time: 5000 }, { info: 'link4', time: 1000 }, { info: 'link5', time: 1200 }, { info: 'link6', time: 2000 }, { info: 'link7', time: 800 }, { info: 'link8', time: 3000 }, ];
function loadImg(url) { return new Promise((resolve, reject) => { console.log("----" + url.info + " start!"); setTimeout(() => { console.log( url.info + " OK!!!"); resolve(); }, url.time) }) };
function multiTask(tasks, func, limit) { let squ = [].concat(tasks);
let promises = [];
promises = squ.splice(0, limit).map((task, index) => { return func(task).then(() => { return index }) })
return squ.reduce((res, task) => { return res.then(() => { return Promise.race(promises); }).then((num) => { promises[num] = func(task).then(() => { return num; }) }) }, Promise.resolve()).then(() => { return Promise.all(promises) }) }
multiTask(urls, loadImg, 3).then(() => { console.log("都完事儿了!") })
|