Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript callback style - Moving to promises

Tags:

javascript

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.

like image 284
Gerard Downes Avatar asked Feb 16 '23 22:02

Gerard Downes


1 Answers

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.

like image 97
Daniel A. White Avatar answered Feb 24 '23 20:02

Daniel A. White