goodvibration
goodvibration

Reputation: 6206

How can I use 'finally' within a 'Promise' clause in NodeJS?

I want something like this:

let promises = [];
for (let i = 0; i < some_length; i++) {
    let output = '';
    promises.push(some_func(i)
        .then((result) => {
            output = result;
        })
        .catch((error) => {
            output = error.message;
        })
        .finally(() => {
            console.log(output);
        })
    );
}
return Promise.all(promises);

But I get a runtime error .then(...).catch(...).finally is not a function.

How can I resolve this?

Upvotes: 1

Views: 7322

Answers (2)

Forivin
Forivin

Reputation: 15508

Node 10 finally added support for it. Tested with node 10.7.0.

Promise.resolve().finally(() => {
    console.log("It finally works!")
})

It finally works!

(Chrome and Firefox also support it btw.)

Upvotes: 2

AmerllicA
AmerllicA

Reputation: 32552

Actually, I Think your some-func function isn't return Promise, with returning JavaScript Promisees the then, catch and finally has meaning, so I think you must declare some_func function as a new instance of Promise object, see below code:

let promises = [];
for (let i = 0; i < some_length; i++) {
    let output = '';
    let some_func = (i) => {
       return new Promise(function(resolve, reject) {
            setTimeout(resolve(`success: ${i}`), 100, 'foo');
       });
    }
    promises.push(some_func(i)
        .then((result) => {
            output = result;
        })
        .catch((error) => {
            output = error.message;
        })
        .finally(() => {
            console.log(output);
        })
    );
}
return Promise.all(promises);

Maybe this code have some other errors, I don't know because I do not test it, but undoubtedly your error is for just like I said in above sentences.

Upvotes: 0

Related Questions