简体   繁体   中英

How to pass a args from a jQuery defered

I have a Backbone model that fetch some data, process the data and then a function should get the processed data.

$.when(model.fetch())
  .done(function(){
    return model.processData()
  })
  .then(function(processedData){
    //make something with the processed data
  })

Unfortunately the then method get the result from the model.fetch() call and not the return value of the done function

You have to use .then instead of .done . .then returns a new promise which is resolved with the value the callback function returns.

.done on the other hand returns the original promise object and the return value of the callback is simply ignored.

More information can be found in the documentation (emphasize mine):

As of jQuery 1.8, the deferred.then() method returns a new promise that can filter the status and values of a deferred through a function, replacing the now-deprecated deferred.pipe() method. The doneFilter and failFilter functions filter the original deferred's resolved / rejected status and values. The progressFilter function filters any calls to the original deferred's notify or notifyWith methods. These filter functions can return a new value to be passed along to the promise's .done() or .fail() callbacks , or they can return another observable object (Deferred, Promise, etc) which will pass its resolved / rejected status and values to the promise's callbacks. If the filter function used is null , or not specified, the promise will be resolved or rejected with the same values as the original.

To intercept , modify or filter data from a done handler to further calls, you can use the .pipe() method.

Even if in your example, you could just entirely replace the .done() , with your .then handler directly, it could also look like:

$.when(model.fetch())
  .pipe(function() {
      return model.processData();
  })
  .then(function(processedData){
    //make something with the processed data
  });

Of course this doesn't make too much sense as mentioned above, but think about the possibilites of .pipe() anyway. It can be a very handy tool.

$.when() should not be necessary.

Here are two possibilities :

model.fetch().then(function() {
    return model.processData()
}).then(function(processedData){
    //make something with the processed data
});

or, if processData() is synchronous :

model.fetch().done(function() {
    var foo = model.processData();
    //make something with the processed data, foo
});

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