Created
February 10, 2018 16:21
-
-
Save edtoken/4b43fb55d9b9fc5798b04a1c0dffcbe0 to your computer and use it in GitHub Desktop.
Mock for ajax parallel requests
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
const call = (function() { | |
const maxParallelCalls = 5; | |
let activeCalls = 0; | |
let requestsStack = []; | |
// outside promise proxy | |
const Defer = function() { | |
this.promise = new Promise((resolve, reject) => { | |
this.resolve = resolve; | |
this.reject = reject; | |
}); | |
}; | |
// your library async call | |
const axiosCall = data => { | |
return new Promise((resolve, reject) => { | |
console.log("start", data.path); | |
setTimeout(() => { | |
resolve([data.path, data.start, new Date()]); | |
// handle new calls from stack | |
activeCalls -= 1; | |
handle(); | |
}, 0.1 + Math.random() * (4 + 1 - 0.1)); | |
}); | |
}; | |
// handler - make new requests | |
const handle = () => { | |
if (activeCalls >= maxParallelCalls) { | |
return; | |
} | |
while (activeCalls < maxParallelCalls && requestsStack.length) { | |
activeCalls += 1; | |
const data = requestsStack.shift(); | |
axiosCall(data).then(r => data.defer.resolve(r)); | |
} | |
}; | |
return function(type, path, query, body) { | |
const data = { | |
type, | |
path, | |
query, | |
body, | |
defer: new Defer(), | |
created: new Date() | |
}; | |
requestsStack.push(data); | |
handle(); | |
return data.defer.promise; | |
}; | |
})(); | |
const get = (path, query) => { | |
return call("get", path, query); | |
}; | |
const post = (path, query, body) => { | |
return call("post", path, query, body); | |
}; | |
let c = 50; | |
while (c) { | |
c -= 1; | |
get(`api/user/${c}`).then(resp => { | |
console.log("FINALLY SUCCESS", resp[0]); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment