Promise resolve even in case of error and trigger then next function

promise error handling
promise then
promise.all parallel
promise.reject vs throw
throw error in promise chain
promise chaining
async/await
try/catch promise

In some cases, 'getData' will throw an error, but I need to resolve it anyhow. How do I resolve 'getData' and ensure 'updateInfo' is called even if 'getData' throws an error?

getData(this.props.data, {})
  .then(
    () => updateInfo('UPDATE_INFO', path, data)
  );

How do I fix this?

Promise.resolve(
  getData(this.props.data, {}))
    .then(
      () => updateInfo('UPDATE_INFO', path, data)
    );

Instead of resolving the promise intentionally, if you wish to take an action on both error and success case, you can use .finally on Promise

getData(this.props.data, {}).finally(() => updateInfo('UPDATE_INFO', path, data));

Error handling with promises, When a promise rejects, the control jumps to the closest rejection handler. new Promise ( ( resolve , reject ) => { throw new Error ( "Whoops! If we throw inside .​catch , then the control goes to the next closest error handler. the unhandledrejection handler triggers, and gets the event object with the  Promise resolve() method: Promise.resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happend: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state.

One thing that's not immediately clear from your example is if path and data are returned by getData() or not, which changes the answer a bit.

If you want to execute the same callback regardless of whether the returned promise resolves or rejects (and you don't need to get path and data from getData()), you can use Promise.prototype.finally():

getData(this.props.data, {})
  .finally(() => updateInfo('UPDATE_INFO', path, data));

Alternatively, if you want to have different behavior depending on whether the promise resolves or rejects (i.e. path and data are returned by getData()), you can do something like:

getData(this.props.data, {})
  .catch(e => /* handle error */) // If this callback doesn't throw an error or return a promise that rejects, it returns a resolved promise
  .then((path = null, data = {}) => updateInfo('UPDATE_INFO', path, data));

Promise, And even if something goes very wrong, say, a fire in the studio, so that then changes to value when resolve(value) called or error when let promise = new Promise ( function ( resolve , reject ) { // the In case something goes wrong, the executor should call reject . We'll see that in the next chapters. Normally, such .catch doesn’t trigger at all. But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it. Implicit try…catch

The proper way to do it would be with Promise.finally(), but if you don't have that, you could trigger your next function in both the then() and catch() phase:

getData(this.props.data, {})
    .then(
        () => updateInfo('UPDATE_INFO', path, data)
    ).catch(
        () => updateInfo('UPDATE_INFO', path, data)
    );

Which you could refactor into:

const update = updateInfo.bind(null,'UPDATE_INFO', path, data);
getData(this.props.data, {})
    .then(update)
    .catch(update);

Or more simply:

const update = updateInfo.bind(null,'UPDATE_INFO', path, data);
getData(this.props.data, {}).then(update,update);

Promise.prototype.catch(), The catch() method returns a Promise and deals with rejected cases only. This means that you have to provide an onRejected function even if you want to fall back to an undefined result const promise1 = new Promise((resolve, reject) => {. 2 Note the examples below are throwing instances of Error. You could also return a Promise, in which case that Promise is what will be returned (eventually resolving or rejecting). In general, it's not wise to define both the resolved and rejected path in the same .then() though: PROMISE.then(fn).catch(fn) is a much safer/clearer practice, because then any errors in the first .then() will be caught by catch.

If you don't want to use finally either because of an older version of Node or not a bluebird promise.

.then accepts the second parameter for rejection of promise

getData(this.props.data, {})
    .then(
        () => updateInfo('UPDATE_INFO', path, data), (error) => updateInfo('UPDATE_INFO', path, data)
    );

Or implement the same code in .catch as well

getData(this.props.data, {})
    .then(
        () => updateInfo('UPDATE_INFO', path, data)
    ).catch(error => {
        console.log(error)
        return updateInfo('UPDATE_INFO', path, data)
    })

All you need to know about Promise.all, Promise.all takes Async operations to the next new level as it helps you to get resolved or any of the ten promises get rejected with an error. You need to execute all the promises even if some have failed, Use cases of Promise.all users. return triggerMailForUser(user) // Async function to send the  const promise = new Promise (function (resolve, reject) {setTimeout (function {resolve ('Promise returns after 1.5 second!');}, 1500);}); promise. then (function (value) {console. log (value); // Promise returns after 1.5 second!}); We defined the Promise object with a new keyword and It is also knows as constructor. A Promise constructor is

How use Promise.all to handle multiple JavaScript promises even , Even though p1 and p3 resolve, the Promise.all() will fail and log an error This is expected behavior, but in our case, we still want to use the To trigger a 'failed​' http request, I'll add some logic to reject the promise if no url is passed to the function. .catch(function(err){ //return error; return err; }); } var p1  // using a resolved promise, the 'then' block will be triggered instantly, // but its handlers will be triggered asynchronously as demonstrated by the console.logs const resolvedProm = Promise.resolve(33); let thenProm = resolvedProm.then(value => { console.log("this gets called after the end of the main stack. the value received and returned is: " + value); return value; }); // instantly logging the value of thenProm console.log(thenProm); // using setTimeout we can postpone the execution

Error handling with async/await and promises, n² ways to shoot , Async await error handling has a bunch of edge cases. Yes, but only if the function was called with the await syntax, and only if resolve() has not been called for the promise Well, how do you even tell if an error in a promise is unhandled? A small, but quite important difference between a function that returns a Promise and an async function. Tagged with javascript, asyncawait, promise, catch.

You're Missing the Point of Promises · GitHub, The point of promises is to give us back functional composition and error with Node.js 0.1's EventEmitter -based "promises" (which weren't even then able). the state of the deferred from the first then to the next unless a new deferred is (​resolved/rejected) promises instead of relying on then() returning a promise for me  The catch () method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.prototype.then (undefined, onRejected) (in fact, calling obj.catch (onRejected) internally calls obj.then (undefined, onRejected) ). This means that you have to provide an onRejected function even if you want to fall back to an undefined result value - for example obj.catch ( () => {}).

Comments
  • with finally you need to use the .then and .catch also. as you will not be catching the error if there's any.
  • ok, How about rejecting the 'getData()' call in case it fails, and just call 'updateInfo'?
  • @Sunny then you just need finally block.
  • @AZ_ catch and then are needed only when you need to do success and error handling separately too. I don't think for the OP, there is a need to use .then and .catch too
  • I mean if getData() is fine, then make both getData() and updateInfo() calls, otherwise just make updateInfo() call. How should that be handled?
  • No, path and data are not returned by getData()
  • Then Promise.prototype.finally() is definitely what you want!