简体   繁体   中英

JavaScript callback style - Moving to promises

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.

The style that you're describing is generally called promises. jQuery has promises, but their documentation calls them "Deferreds" and it is an implementation of the Promises/A spec; there are a couple other promises libraries out there, including Q . (YUI also contains a promises implementation.)

There have been a bunch of recent (mid-2013) blog posts about promises, so it should be easy to find more information about them, both as a pattern and about specific implementations. It's worth digging into the source code of a couple of the implementations to see the nuts-and-bolts, but at a high-level, you can think of promises like this:

  • You wrap an asynchronous function in a promise and it is called.
  • The promise itself is then returned, meaning that you can save a reference to it in a variable.
  • The promise itself will be resolved (or "fulfilled") when the async function you called is complete.
  • You can then call done on the resolved promises, passing your callback function as the argument to done .

Isn't it simply this here:

Function

doSomething = new Object();

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

So it is just an Object extended with a member "success" that is a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM