To clarify, your goal is to initiate all promises simultaneously and showcase the results of each promise in a specific order as they are received, right?
In that scenario, my approach would be:
let slow = new Promise((resolve) => {
setTimeout(function()
{
// Instead of logging here, we resolve with the desired value
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 display the results...
// First, wait for the result of `slow`...
slow.then((result) => {
// Result received...
console.log(result);
// Now await the result of instant...
instant.then((result) => {
// Result obtained...
console.log(result);
// Now await the result of quick...
quick.then((result) => {
// Result acquired...
console.log(result);
}).then((result) => {
// Completed
console.log('finished');
});
});
});
Note that unlike cchamberlain's response, this method does not necessitate waiting for all promises to resolve prior to returning results. It returns the results as they arrive, while maintaining the specified order of results. (To confirm this, adjust the waiting time of quick
to 2500ms, and observe that its result is displayed 500ms after instant
.) Depending on your application, this may be beneficial.
The above code may seem cluttered, but fortunately, it can be significantly streamlined using the new async/await
syntax in ES2017:
let slow = new Promise((resolve) => {
setTimeout(function()
{
// Instead of logging here, we resolve with the desired value
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 show the results...
async function logResults(...promises) {
for (let promise of promises) {
console.log(await promise);
}
}
logResults(slow, instant, quick).then(() => console.log('finished'));
Test in Babel. Note: Presently, the above code won't work in modern browsers without Babel support (as of October 2016). In future browsers, it will.