How to deal with promise rejection

committed toIt is one of the best things that have happened to JavaScript in the past few years.

When we call the function that returns the promise, we willthen()The promised method, when the function is promised to runsolve.

This is usingExtract API:

fetch('/data.json')
  .then(response => { 
    console.log(response.status)
  })

What to do if an error occurs during operationfetch()call? Maybe the network is unavailable. Or the network request returned an error.

The promise will be rejected. A promise will look like this:

const thePromise = new Promise((resolve, reject) => {

})

In the promise, we passed 2 parameters and 2 functions. In the body, if all goes well, the resolve() function will be called:

const thePromise = new Promise((resolve, reject) => {
  resolve('ok') //you can pass any value
})

If an error occurs, the reject() function will be called:

const thePromise = new Promise((resolve, reject) => {
  reject('error message') //you can pass any value
})

If there is something bad, we must deal with promise rejection. We usecatch()Commitment method:

thePromise
  .catch(error => {
    console.error(error)
  })

We must always add onecatch(), Otherwise the promise willFail silently.

We can chaincatch()To athen()method:

thePromise
  .then(response => { 
    console.log(response)
  })
  .catch(error => {
    console.error(error)
  })

Even more, if you have a series of commitments:

const thePromise = new Promise((resolve, reject) => {
  resolve({
    doSomething: function() {
      return new Promise((resolve, reject) => {
        reject('error!') //you can pass any value
      })
    }
  })
})

thePromise .then(response => { return response.doSomething() }) .then(response => { console.log(response) }) .catch(error => { console.log(error) })

In this case, ifthePromiseRejected, execution will jump directly tocatch()method.

You can addcatch()In the middle of the two methodsthen()Method, but when something bad happens, you will not be able to break the shackles. And return valuecatch()(Which containsundefinedThe value (if not specified) will be passed to the followingthen().

I think it's better to leavecatch()At the end of the chain, and use it to handle all possible errors.

I think error handling is the bestAsync/await, But sometimes we can’t avoid using promises, so you can do it.

Download mine for freeJavaScript beginner's manual


More js tutorials: