1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • `finally` is not yet in the standard, and therefore not supported by Node. You can use [this polyfill](https://stackoverflow.com/a/32362233/1048572) though – Bergi Oct 26 '17 at 07:07
  • @Bergi: OK, so in other words, switch to the (newer) `async`/`await` paradigm, which we are planning to do at some point anyway, but were hoping that there would be a similar mechanism in `Pomise` paradigm. Thank you!!! – goodvibration Oct 26 '17 at 07:24
  • 1
    @goodvibration `async`/`await` is still using the promise paradigm, it just has more syntactic sugar. – Bergi Oct 26 '17 at 08:35
  • Btw, for the example in your question I would recommend to simplify to `some_func(i).catch(err => err.message).then(console.log)` (which is probably even better than any `finally`+`await`, as there you always need that `output` variable) – Bergi Oct 26 '17 at 08:37

2 Answers2

2

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.)

Forivin
  • 14,780
  • 27
  • 106
  • 199
0

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.

AmerllicA
  • 29,059
  • 15
  • 130
  • 154