ajhsu / blog

The external storage of my brain.
3 stars 0 forks source link

Promise re-throwing #23

Open ajhsu opened 7 years ago

ajhsu commented 7 years ago

Promise re-throwing

The benefits of re-throwing is about handling errors from each stage correctly; And prevent the process from being stopped in the middle of the pipelines.

Example

Basic

// Promise Error Re-throwing
new Promise((y, n) => {
  throw new Error('error1');
})
.then(res => {
  console.log('stage 1');
})
.catch(err => {
  console.log('error handler of stage 1');
  console.log(err);
})
.then(res => {
  console.log('stage 2');
})
.catch(err => {
  console.log('error handler of stage 2');
  console.log(err);
});

Same as

new Promise((y, n) => {
  throw new Error('error1');
})
.then(res => {
  console.log('stage 1');
}, err => {
  console.log('error handler of stage 1');
  console.log(err);
})
.then(res => {
  console.log('stage 2');
}, err => {
  console.log('error handler of stage 2');
  console.log(err);
});

Handlers can be extracted and simplified as below

const stage1 = {
  success: res => {
    console.log('stage 1');
  },
  fail: err => {
    console.log('error handler of stage 1');
    console.log(err);
  }
};

const stage2 = {
  success: res => {
    console.log('stage 2');
  },
  fail: err => {
    console.log('error handler of stage 2');
    console.log(err);
  }
};

new Promise((y, n) => {
  throw new Error('error1');
})
.then(stage1.success, stage1.fail)
.then(stage2.success, stage2.fail);