Is this the correct way to convert jQuery Deferred
to a Promise
?
var p = Promise.resolve($.getJSON('api/values', null));
Are there any other ways to do this?
What are the limitations? I've read somewhere that jQuery deferred does not support exceptions, so I assume that a promise created out of a deferred would neither. Is this correct?
A deferred object is an object that can create a promise and change its state to resolved or rejected . Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the producer of the value. A promise is, as the name says, a promise about future value.
The Deferred object, introduced in jQuery 1.5, is a chainable utility object created by calling the jQuery. Deferred() method. It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
The deferred. promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.
Promises are a way to implement asynchronous programming in JavaScript(ES6 which is also known as ECMAScript-6). A Promise acts as a container for future values.
Yes it should, the Promise.resolve() API supports thenable as argument. So passing a jquery defer object would work just fine.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve#Resolving_thenables_and_throwing_Errors
I am not sure if that would work. I would recommend:
var p = new Promise(function (resolve, reject) { $.getJSON('api/values', null) .then(resolve, reject); });
preferably you could create an adaptorfunction like:
var toPromise = function ($promise) { return new Promise(function (resolve, reject) { $promise.then(resolve, reject); }); }); var p = toPromise($.getJSON('api/values', null));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With