O'Reilly logo

Async JavaScript by Trevor Burnham

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Replacing Callbacks with Promises

In a perfect world, every function that started an async task would return a Promise. Unfortunately, most JavaScript APIs (including the native functions available in all browsers and in Node.js) are callback-based, not Promise-based. In this section, we’ll see how Promises can be used with callback-based APIs.

The most straightforward way to use Promises with a callback-based API is to create a Deferred and pass its trigger function(s) as the callback argument(s). For example, with a simple async function like setTimeout, we’d pass our Deferred’s resolve method.

 
var​ timing = ​new​ $.Deferred();
 
setTimeout(timing.resolve, 500);

In cases where an error could occur, we’d write a callback that conditionally ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required