Domysee
Domysee

Reputation: 12846

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?

Upvotes: 33

Views: 12435

Answers (3)

nox
nox

Reputation: 351

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

Upvotes: 12

Shishir Arora
Shishir Arora

Reputation: 5923

I would prefer composition:

const successCb1 = ()=>$.getJSON('api/values'),
successCb2 = (json)=>alert(json),
errorCb = (e)=>alert(e);
Promise
   .resolve()
   .then(successCb1)
   .then(successCb2)
   .catch(errorCb);

Upvotes: 2

Andreas Møller
Andreas Møller

Reputation: 849

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));

Upvotes: 12

Related Questions