tkrkt
8/5/2017 - 2:35 AM

[JS] Skip specific process on promise chain

[JS] Skip specific process on promise chain

const skipKey = Symbol('skip');
const skip = (key, value) => {
  throw {[skipKey]: key, value: value};
};
const recover = (key, error) => {	
  if (error && error[skipKey] === key) {
    return error[value];
  } else {
    throw error;
  }
};

// usage
anyAsyncFunction()
  .then(result => {
    if (result.needsTransformA) {
      return result;
    } else {
      skip('skipTransformA', result);
    }
  })
  .then(result => {
    return transformA(result);
  })
  .catch(error => {
    return recover('skipTransformA', error);
  })
  .then(transformed => {
    // ...
  });

// of cource this is much better
async function withAsyncAwait(() => {
  let result = await anyAsyncFunction();
  if (result.needsTransformA) {
    result = await transformA(result);
  }
  // ...
});