简体   繁体   中英

Skip a jQuery promise in a chain of promises depending on response

I have a chain of jQuery promises, but I would like to skip one of them depending on the response of an earlier promise.

My code is something like:

getMoney()
  .then(getBeer)
  .then(getFireworks)
  .then(getLighterfluid)
  .then(getCrazy);

If the promise in my getFireworks function returns something like 'No fireworks available', then I want to skip the getLighterFluid promise, and move on to getCrazy.

How could I approach this with my current setup? Or do I need to rework this?

There are many ways around this, but essentially you have to change something in the structure of the chain, or the functions themselves.

In this case, I'd wrap the getLighterfluid with a helper like this:

getMoney()
  .then(getBeer)
  .then(getFireworks)
  .then(function(val) { if(val != 'No fireworks available') return getLighterfluid(val); })
  .then(getCrazy);

You could generalize this pattern if you need to use it a lot:

function conditionally(predicate, handler) {
  return function(val) {
    if(predicate(val) {
      return handler(val);
    }
  };
}

function notEqualFunc(val) {
  return function(v) {
    return v != val;
  };
}

getMoney()
  .then(getBeer)
  .then(getFireworks)
  .then(conditionally(notEqualFunc('No fireworks available'), getLighterfluid))
  .then(getCrazy);

You could create whatever predicate prototype you need instead of notEqualFunc and make the code quite descriptive.

Assuming that getFireworks resolves to [ { type: "rocket" } ] or similar then getLighterFluid could just do nothing.

function getLighterFluid(fireworks) {
    if (!fireworks.length) return;

    //go get that lighter fluid
}

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