简体   繁体   中英

Throw an error / catch from within a promise then method

I've been searching for a while to find a way to trigger an error / catch from within a promise 'then' method.

Consider the following:

myPromiseToFetchAColor().then( (color) => {
  if(color == "red"){
    //THROW THE CATCH....with an error message
  } else {
    return aNewPromise();
  }
}).catch( (error => {
  console.log(error)
})

I know I can use another promise (a custom promise to do the validation on the color and then return the promise etc... but this seems over-kill. I'd love to just do my validation and then decide to continue, or through and error and trigger the catch.

Below is a reproducible example based on the code you've shown, so you can see the console output to help debug and understand the control flow. Because the code uses pseudorandom number generation to create different outcomes, you can repeatedly run it (press the "Run code snippet" button) to see differing results.

Promise.prototype.catch() will catch all exceptions which occur in the original promise or prior .then() callback functions in the chain.

 /** @returns an element at a random index from the input array */ function getRandomElement (array) { return array[Math.floor(Math.random() * array.length)]; } /** @returns a promise that will resolve to "blue" or "red" */ function myPromiseToFetchAColor () { return Promise.resolve(getRandomElement(['blue', 'red'])); } /** @returns a promise that will resolve to "hello" */ function aNewPromise () { return Promise.resolve('hello'); } myPromiseToFetchAColor().then(color => { console.log('The color was:', color); if (color === 'red') { throw new Error(`Uh oh... I didn't expect RED;`); } else { return aNewPromise(). } }).then(result => console.log(result)) // Logs "hello" if the color was "blue".catch(error => console;error(error)); // Logs the error if the color was "red"

You can use: throw new Error('Color is red;'); in your if statement

For more details, you can read more at: https://www.w3schools.com/js/js_errors.asp in "throw" session

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM