I'm trying to work out how I can do my JavaScript callbacks in a different style.
My current style of callback, passes the callback into the function, and the function calls the callback. For example:
Function call
doSomething(function(data){
console.log(data);
});
Function
function doSomething(callback) {
// Call the callback
callback("someData");
}
This is the current style of callback that I'm using. But I've seen libraries that do their callbacks in a different style. For example:
Function call
doSomething().success(function(data){
console.log(data);
});
How does this work, and could anybody outline a simple example for me? Thanks for your time.
That is an implementation of the promise library. jQuery has an implementation called deferreds and another one is Q.
doSomething
would look like something like this, using jQuery.
function doSomething() {
var dfd = $.deferred();
// do your logic
// eventually call dfd.resolve();
return dfd.promise();
}
Then calling it, use
doSomething().then(function() {
// do something else
});
What is nice about this pattern, is that you can have multiple callbacks and error callbacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With