Q.Promise() – another way to create promises

Q.Promise is an alternative promise-creation API that has the same power as the deferred concept, but without introducing another conceptual entity.

Let's rewrite the preceding requestOkText example using Q.Promise:

function requestOkText(url) { return Q.Promise(function(resolve, reject, notify) { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onload = onload; request.onerror = onerror; request.onprogress = onprogress; request.send(); function onload() { if (request.status === 200) { resolve(request.responseText); } else { reject(new Error("Status code was " + request.status)); } } function onerror() { reject(new Error("Can't XHR " + JSON.stringify(url))); } function onprogress(event) ...

Get Mastering JavaScript Promises 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.