Last active
September 4, 2018 11:21
-
-
Save poberwong/7785eb8fabae85ed7d3baeb6c991b964 to your computer and use it in GitHub Desktop.
This file contains 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
let wxRequest = function (params) { | |
setTimeout(() => { | |
params.success(params.message) | |
}, params.time) | |
} | |
const limitedRequest = function (max) { | |
const LIMIT = max || 5 | |
const cacheQueue = [] | |
let count = 0 | |
function request (params) { | |
return (new Promise((resolve, reject) => { | |
wxRequest({ | |
...params, | |
success: (...params) => { | |
finishReq() | |
resolve(...params) | |
}, | |
fail: (...params) => { | |
finishReq() | |
reject(...params) | |
} | |
}) | |
})) | |
} | |
function finishReq () { | |
count-- | |
let cacheHead = cacheQueue.shift() | |
cacheHead && cacheHead() | |
} | |
return function (params) { | |
if(count > LIMIT) { | |
return (new Promise((resolve) => { | |
cacheQueue.push(function () { | |
resolve(request(params)) | |
}) | |
})).then(req => req) | |
} else { | |
let curReq = request(params) | |
count++ | |
return curReq | |
} | |
} | |
} | |
const limitedReq = limitedRequest() | |
for (let i = 0; i < 5; i++) { | |
limitedReq({ | |
time: 1000, | |
message: 'i = ' + i | |
}).then(res => console.log(res)) | |
} | |
================================ | |
// Without Closure | |
const LIMIT = max || 5 | |
const cacheQueue = [] | |
let count = 0 | |
function request (params) { | |
return (new Promise((resolve, reject) => { | |
wxRequest({ | |
...params, | |
success: (...params) => { | |
finishReq() | |
resolve(...params) | |
}, | |
fail: (...params) => { | |
finishReq() | |
reject(...params) | |
} | |
} | |
})) | |
} | |
function finishReq () { | |
count-- | |
let cacheHead = cacheQueue.shift() | |
cacheHead && cacheHead() | |
} | |
function limitedRequest (params) { | |
if(count > LIMIT) { | |
return (new Promise((resolve) => { | |
cacheQueue.push(function () { | |
resolve(request(params)) | |
}) | |
})).then(req => req) | |
} else { | |
let curReq = request(params) | |
count++ | |
return curReq | |
} | |
} | |
// Aync/await | |
async function limitedRequestAsync (params) { | |
return await limitedRequest(params) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about async/await ?