Skip to content

Instantly share code, notes, and snippets.

@rupeshtiwari
Last active August 6, 2018 18:21
Show Gist options
  • Save rupeshtiwari/363c37cc63fd203c3fcbf7d923fbc7fa to your computer and use it in GitHub Desktop.
Save rupeshtiwari/363c37cc63fd203c3fcbf7d923fbc7fa to your computer and use it in GitHub Desktop.
In order to make your program reactive you need promise dataType. In below 2 examples I am explaining how to create promise object and return data or error message.
// getData function is pretending that it is fetching data and after 2 second it received data.
// $ is jQuery
function getData() {
//creating on dererred object
var deferred = $.Deferred();
// after 2 second resolve promise with data.
setTimeout(function() {
deferred.resolve([1,2,3]);
}, 2000);
return deferred.prmise(); //return promise
}
// how to use it ? below is one example
getData().done(function(data){
alert(data);
});
// getData function is pretending that it is erroring out after 2 second.
// $ is jQuery
function getData() {
//creating on dererred object
var deferred = $.Deferred();
// after 2 second reject promise with message
setTimeout(function() {
deferred.reject('Server Error Happened');
}, 2000);
return deferred.prmise(); //return promise
}
// how to use it ? below is one example
getData()
.done(function(data){
alert(data);
})
.error(function(message){
alert(message);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment