Search code examples
javascriptpromisebluebirdchaining

How to reject a promise i did not create?


Fairly new to promises here, and i was wondering..

After taking a look at bluebird package for handling promises:

  • Creating a Resolver
  • Resolve on success / reject on failure
  • Returning the created resolver promise property

I've been wondering how can i achieve the same effect of rejecting a promise to raise a catch using packages that already create the promise, and I'm just using their .then chain?

What i mean is, using reject on my create resolver will eventually raise a catch to the user of this function.

How can i raise a catch if i dont have the resolver. chaining the promise as follows :

function doSomthing(): Promise<someValue>
    return somePackage.someMethodWithPromise().then((result)=> {
        return someValueToTheNextThen;
    })
}

The only way I've seen some packages achieving that is by returning a { errors, result } object so that the next then can check if there are any errors and react to it, but I want to raise a catch and not check for errors in every single then i have..

Hope i made myself clear, please let me know if anything is missing.

Thanks in advance for the help!


Solution

  • The .then just returns a Promise as well. You can simply created a rejected promise and return it from there if you determine there’s an error.

    return somePackage.someMethodWithPromise().then(result => {
      if (result.erroneous()) return Promise.reject('erroneous data');
      return someValueToTheNextThen;
    })
    

    You can also simply throw anError; from the then which would also be catched in a catch block.