javascriptasynchronouspromisepromise.all

Can I have multiple .finally() as well as multiple .catch() in Promise.all()?


var p1 = new Promise((resolve, reject) => {

        resolve('p1');
    });

    var p2 = new Promise((resolve, reject) => {
        resolve('p2');
    });
    Promise.all([
        p1.finally(() => { console.log("p1 completed"); }),
        p2.finally(() => { console.log("p2 completed"); }),
    ]).then(values => {
        console.log(values[0]);
        console.log(values[1]);
    }).finally(() => {
        console.log("all() completed");
  

I think I've only seen examples on the web with a single .finally() at the end [1]: https://i.sstatic.net/HeQV8.png


Solution

  • Sure, finally is a chainable promise method just like catch (with the only difference that its callback does not take a parameter). You can use it as many times as you want, on any promise.

    Promise.all([
        p1.finally(() => { console.log("p1 completed"); }),
        p2.finally(() => { console.log("p2 completed"); }),
    ]).finally(() => {
        console.log("all() completed");
    })