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 ...
Get Async JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.