The target
The ability to control the Promise request queue by limiting the number of concurrent inputs
implementation
Ideas:
- Maintenance through closures
The result array
.The quantity being processed
.The amount that has been processed
2. Encapsulate the run method as the core code 1. 2. When all promises have been processed, the resolve method is triggered and resArr is printed
- Concurrency is achieved through a for loop, executing the run method
Type: (limitNum,promiseList)=>Promise
function createLimitPromise(limitNum, promiseListRaw) {
let resArr = [];
let handling = 0;
let resolvedNum = 0;
let promiseList = [...promiseListRaw]
let runTime = promiseListRaw.length
return new Promise(resolve= > {
// Execute limitNum times concurrently
for (let i = 1; i <= limitNum; i++) {
run();
}
function run() {
if(! promiseList.length)return
handling += 1;
handle(promiseList.shift())
.then(res= > {
resArr.push(res);
})
.catch(e= > {
//ignore
console.log("catch error");
})
.finally(() = > {
handling -= 1;
resolvedNum += 1;
if(resolvedNum === runTime){
resolve(resArr)
}
run();
});
}
function handle(requestFn) {
return new Promise((resolve, reject) = > {
requestFn().then(res= > resolve(res)).catch(e= >reject(e)); }); }}); }Copy the code
test
— The test case before 2020/01/07 was misleading, it has been updated —
Generate six functions that encapsulate promise for the specified delay, simulating an HTTP request
/ * * *@param {Array<number>} Delay list@return {Array<Function>} A list of functions that encapsulate delay **/
const createMockHttpRequest = (mockDelayList) = > {
let mockDelay = mockDelayList.map((delay, index) = > ({id: index, delay}))
return mockDelay.map((delayInfo) = > () = > new Promise(resolve= > {
console.log('run: ', delayInfo.id, delayInfo.delay)
setTimeout(() = > {
console.log('resolved: ------->', delayInfo.id, delayInfo.delay)
resolve(delayInfo.id);
}, delayInfo.delay)
}))
}
const httpRequestList = createMockHttpRequest([200.20.100.300.600.30])
createLimitPromise(3, httpRequestList);
Copy the code
The output
run: 0 200 source/_posts/test.js:4
run: 1 20 source/_posts/test.js:4
run: 2 100 source/_posts/test.js:4
resolved: -- -- -- -- -- -- -- >1 20 source/_posts/test.js:6
run: 3 300 source/_posts/test.js:4
resolved: -- -- -- -- -- -- -- >2 100 source/_posts/test.js:6
run: 4 600 source/_posts/test.js:4
resolved: -- -- -- -- -- -- -- >0 200 source/_posts/test.js:6
run: 5 30 source/_posts/test.js:4
resolved: -- -- -- -- -- -- -- >5 30 source/_posts/test.js:6
resolved: -- -- -- -- -- -- -- >3 300 source/_posts/test.js:6
resolved: -- -- -- -- -- -- -- >4 600 source/_posts/test.js:6
Copy the code