Skip to content

Instantly share code, notes, and snippets.

@guangtuan
Last active April 18, 2018 08:08
Show Gist options
  • Save guangtuan/4eaad848b64561454c0c6e9dad497245 to your computer and use it in GitHub Desktop.
Save guangtuan/4eaad848b64561454c0c6e9dad497245 to your computer and use it in GitHub Desktop.
nodejs
const aRequest = new Promise(resolve => {
setTimeout(() => {
resolve('3s')
}, 3000);
});
const bRequest = new Promise(resolve => {
setTimeout(() => {
resolve('1s')
}, 1000);
});
const aHandler = data => {
console.log('first handler', data)
}
const bHandler = data => {
console.log('second handler', data)
}
const requests = [aRequest];
const handlers = [aHandler];
const needBRequest = Math.random() > 0.5;
if (needBRequest) {
requests.push(bRequest);
handlers.push(bHandler);
}
Promise.all(requests).then(responses => {
while (responses.length) {
handlers.shift()(responses.shift())
}
});
@guangtuan
Copy link
Author

If you cannot ensure length of your requests array, you can handle responses like this way cause a handler handles a request and Promise.all() resolve result in order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment