Created
August 5, 2016 15:21
-
-
Save swapnilshrikhande/2bc76ddc59be5fccfc1518e57c6b7f35 to your computer and use it in GitHub Desktop.
How deferred chaining works ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var performParent = function(){ | |
//perform 1st async | |
var promise1 = performAsync('func1',5); | |
// We want to chain two async operations | |
promise1.then(function(data){ | |
console.log('data from 1st async operation',data); | |
//perform second async operation | |
//this return links second aync deferred to first one | |
return performAsync('func2',10); | |
}).then(function(data){ | |
console.log('finalData',data); | |
console.log('both done'); | |
}); | |
}; | |
var performAsync = function(nameStr,count){ | |
var deferred = $.Deferred(); | |
var intervalId = window.setInterval(function(){ | |
--count; | |
if(count==0){ | |
clearInterval(intervalId); | |
deferred.resolve({idea:nameStr}); | |
return; | |
} | |
console.log(nameStr+':'+count); | |
}, count*100); | |
return deferred.promise(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment