Sunday 15 March 2015

jquery - Chaining multiple done() callbacks to the same deferred promise -



jquery - Chaining multiple done() callbacks to the same deferred promise -

in short, have 1 general callback fires in case of successful ajax call, followed separate callback functionality depending on method invoked.

this seems work. question if right utilize of promise object , if it's safe assume multiple promise callbacks of same type stack sequentially?

var dfd = $.deferred(), promise = dfd.promise(); promise.done(function(){ console.log(1); }).done(function(){ console.log(2); }); dfd.resolve();

http://jsfiddle.net/4ax4nxbh/

it's right , documented utilize of deferred object in jquery. documentation clearly states:

callbacks executed in order added.

it works differently in other promise libraries , .then preferred .done anyway (explained later in answer). given you're using jquery promises it'll stack fine sequentially if they're synchronous.

so direct reply question yes.

however, can asynchronous code , have chain improve .then:

promise.then(function(){ console.log(1); }).then(function(){ console.log(2); }).then(function(){ homecoming $.get(...); }).then(function(){ console.log(3); // executes after $.get finishes. });

basically, done adds handler , returns same promise , .then returns new promise chained lastly one. in general i'd utilize .done terminate chains , if want maintain homecoming value (the argument of function(){)

jquery promise

No comments:

Post a Comment