Last active
April 18, 2018 08:08
-
-
Save guangtuan/4eaad848b64561454c0c6e9dad497245 to your computer and use it in GitHub Desktop.
nodejs
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 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()) | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.