Search code examples
javascriptpromisees6-promise

How to sort promises in their resolved order not caring about order in arguments


let P1 = new Promise((res, rej) => {
    setTimeout(res("R1"), 2000);
});
let P2 = new Promise((res, rej) => {
    setTimeout(res("R2"), 5000);
});
let P3 = new Promise((res, rej) => {
    setTimeout(res("R3"), 1000);
});

I expect my function to return promises in order they started like this: ["R3", "R1", "R2"]

function preserveOrder([P1, P2, P3]); // should return ["R3, "R1", "R2"]
function preserveOrder([P2, P3, P1]); // should return ["R3, "R1", "R2"]

I can't think of what the best way it is to do this? (since Promise.all() would preserve the order)


Solution

  • You might be looking for

    async function fulfillmentOrder(promises) {
        const results = [];
        await Promise.all(promises.map(promise =>
            promise.then(value => {
                results.push(value);
            })
        ));
        return results;
    }