So to be clear, what you want to do here is kick off all the promises at once and display the results of each promise in a particular order as they come in, correct?
In that case, I'd probably do it like this:
let slow = new Promise((resolve) => {
setTimeout(function()
{
// Rather than log here, we resolve to the value we want to log
resolve('slow');
}, 2000, 'slow');
});
let instant = new Promise((resolve) => {
resolve('instant');
});
let quick = new Promise((resolve) => {
setTimeout(function()
{
resolve('quick');
}, 1000, 'quick');
});
// All Promises are now running. Let's print the results...
// First wait for the result of `slow`...
slow.then((result) => {
// Result received...
console.log(result);
// Now wait for the result of instant...
instant.then((result) => {
// Result received...
console.log(result);
// Now wait for the result of quick...
quick.then((result) => {
// Result received...
console.log(result);
}).then((result) => {
// Done
console.log('finished');
});
});
});
Notice that unlike cchamberlain's answer, this method does not wait for all promises to resolve before it starts returning results. It returns the results as they come in, but without violating your requirement of keeping the results in-order. (To verify this, try changing the wait time of quick
to 2500ms, and observe that its result is printed 500ms after instant
.) Depending on your application, this may be desirable.
The above code is a bit messy, but thankfully with the new async/await
syntax in ES2017 it can be made much cleaner:
let slow = new Promise((resolve) => {
setTimeout(function()
{
// Rather than log here, we resolve to the value we want to log
resolve('slow');
}, 2000, 'slow');
});
let instant = new Promise((resolve) => {
resolve('instant');
});
let quick = new Promise((resolve) => {
setTimeout(function()
{
resolve('quick');
}, 1000, 'quick');
});
// All Promises are now running. Let's print the results...
async function logResults(...promises) {
for (let promise of promises) {
console.log(await promise);
}
}
logResults(slow, instant, quick).then(() => console.log('finished'));
Try in Babel. Note: The above code doesn't currently work in modern browsers without Babel (as of October 2016). In future browsers it will.