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

170
November 23, 2016, at 9:09 PM

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?

Answer 1

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
}
Answer 2

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.

READ ALSO
Using Typeahead Bloodhound inside a jQuery plugin

Using Typeahead Bloodhound inside a jQuery plugin

I have a basic jQuery plugin defined as such:.

388
How to iterate inside respond_to according to rails variables?

How to iterate inside respond_to according to rails variables?

I'm looking for a way to display multiple forms in a table when a new Cars is saved. .

229
How to load webpage in an iframe on click of a link of another iframe

How to load webpage in an iframe on click of a link of another iframe

I have two iframes (say 1 & 2) in a webpage. In the iframe1, I have a hyperlink on click of which, I want to load another webpage in the iframe2.

193
Ajax crossdomain request fail to read responce from remote server

Ajax crossdomain request fail to read responce from remote server

I am sending Ajax request to remote server which must return html advert square but code doesnt work as supposed[nnn]here is the code:.

217