简体   繁体   中英

How to get last resolved promise from a list of resolved promises in Javascript?

Suppose, we have list of promises [p1,p2] . I want to create a function which takes [p1,p2] as arguments and return the last resolved promise ie in this case, the returned promise would be p2 .

The Motivation is I want to implement last() method on Promise object.

 const p1 = new Promise((resolve,reject)=>{
                setTimeout(()=>{resolve("P1 resolved in 3 seconds")},3000)
            });
 const p2 = new Promise((resolve,reject)=>{
                setTimeout(()=>{resolve("P2 resolved in 5 seconds")},5000)
            });

Promise.race([p2,p1]).then(value=>{ console.log(value) // Both promises resolved but P2 is slower
    }) // Expected output : P1 resolved in 3 seconds

 Promise.last([p2,p1]).then(value=>{ console.log(value) // Both promises resolved but P2 is slower
    }) // Expected output : P2 resolved in 5 second.

Pretty simple: just wait for all the promises using standard Promise.all , and put them into an array in the order they fulfilled (when they fulfill) so that you can access the last value:

async function lastResult(promises) {
    if (!promises.length) throw new RangeError("No last result from no promises");
    const results = [];
    await Promise.all(promises.map(p =>
        p.then(v => {
            results.push(v);
        })
    ));
    return results[results.length-1];
}

You can adjust this to handle rejections in the way you want, to return any other (eg first) result, etc. If you really need only the last result, you don't need to store them in an array but can simply keep a single variable that you overwrite every time a promise resolves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM