Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a jQuery Deferred object to an ES6 Promise

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?

like image 913
Domysee Avatar asked Aug 24 '15 07:08

Domysee


People also ask

What is jQuery deferred and promise object?

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.

What is deferred object in jQuery?

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.

What is defer in promise?

The deferred. promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.

What is a ES6 promise?

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.


2 Answers

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

like image 154
nox Avatar answered Sep 20 '22 10:09

nox


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)); 
like image 43
Andreas Møller Avatar answered Sep 21 '22 10:09

Andreas Møller