Last active
December 15, 2017 20:59
-
-
Save ycmjason/51d5601bf74bfae280a313c367b10363 to your computer and use it in GitHub Desktop.
Transform a function into the same function but with limited async calls at the same time.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const limitAsyncCalls = (fn, n) => { | |
const cap = n; | |
let executing_count = 0; | |
let waitings = []; | |
const wait = () => new Promise(res => waitings.push(res)); | |
const execute = async (fn, args) => { | |
executing_count++; | |
const result = await fn(...args); | |
executing_count--; | |
(waitings.shift() || (() => {}))(); | |
return result; | |
}; | |
return async function(){ | |
if(executing_count >= cap) await wait(); | |
return await execute(fn, arguments); | |
}; | |
}; | |
let i = 0; | |
const fn = limitAsyncCalls(async function(n){ | |
const id = i++; | |
console.log(id + ' starts'); | |
return new Promise(res => setTimeout(() => { | |
console.log(id + ' ends'); | |
res(id + n); | |
}, Math.random() * 1000)); | |
}, 2); | |
[0,1,2,3,4,5].map(fn); | |
/* Output: | |
0 starts | |
1 starts | |
0 ends | |
2 starts | |
1 ends | |
3 starts | |
2 ends | |
4 starts | |
3 ends | |
5 starts | |
4 ends | |
5 ends | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment