Search code examples
javascriptasynchronouses6-promise

execution order finally() in promises


I was expecting the finally to run after resolving all promises, but I see that it runs after resolving the first promise. So I have two questions: (1) Is the finally one per promise just like the catch, that is, can I have a finally per promise or because this behavior? (2) If I need a finally to run after resolving all promises, do I need only one at the end, just like catch?

let variable = new Promise((resolve, reject) => {
            
            console.log('empiezo 1era promesa, espero 9');
            setTimeout(() => {
                resolve(1);
            }, 9000);
    })
    .finally(() => {

        console.log('empieza finally');
    })
    .then(data => {
        
        return new Promise((resolve, reject) => {
            
            console.log('1era promesa resulta, empiezo 2da promesa, espero 5 seg');
            setTimeout(() => {
                resolve(2);
            }, 5000);
        });
        
    })
    .then(data => {
        console.log('2da promesa resulta, ya termino todo');
        console.log(data);
    })

Ouput: empiezo 1era promesa, espero 9 empieza finally 1era promesa resulta, empiezo 2da promesa, espero 5 seg 2da promesa resulta, ya termino todo 2

My doubt is because I always see examples with only one finally at the end and this one is executed after resolving all the promises.


Solution

  • All of the then, catch and finally methods are "per promise", the promise they were called on. They all return a new promise that will resolve after the callback(s) have run, and they do not know about any other promises further down the chain (or even in other chains).

    If you want your finally callback to run after all the promises in your chain have settled, you should also chain it in the end.