JavaScript callback style - transition to promises

I am trying to figure out how I can execute my JavaScript callbacks in a different style.

My current callback style passes the callback to the function and the function calls the callback. For instance:

Function call

doSomething(function(data){ console.log(data); }); 

Function

 function doSomething(callback) { // Call the callback callback("someData"); } 

This is the current callback style I'm using. But I saw libraries that execute their callbacks in a different style. For instance:

Function call

 doSomething().success(function(data){ console.log(data); }); 

How does it work, and can someone provide a simple example for me? Thank you for your time.

+4
source share
3 answers

This is an implementation of the promise library. jQuery has an implementation called deferred, and the other is Q.

doSomething will look 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 you like about this template is that you can have multiple callbacks and error callbacks.

+4
source

The style you describe is usually called promises. jQuery has promises, but their documentation calls them “Pending” and is an implementation of the Promises / A spec; There are a couple of other promises libraries, including Q. (YUI also contains an implementation of promises.)

There were a bunch of recent (mid-2013) blog posts about promises, so it would be easy to find more information about them, both in the form of a template and about specific implementations. It’s worth digging into the source code of a couple of implementations to see the nuts and bolts, but at a high level you can think of promises as follows:

  • You end the asynchronous function in the promise and are called.
  • Then the promise itself is returned, which means that you can save the link to it in a variable.
  • The promise itself will be allowed (or "fulfilled") when the asynchronous call function that you called is completed.
  • You can then call done in the allowed promises, passing the callback function as the done argument.
+3
source

Isn't it just here:

Function

 doSomething = new Object(); doSomething.success = function(callback) { // Call the callback callback("someData"); } 

Thus, it is simply an object expanded with the success element, which is a function.

+1
source

Source: https://habr.com/ru/post/1491096/


All Articles