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 limitati
Solution 1:
Yes it should, the Promise.resolve() API supports thenable as argument. So passing a jquery defer object would work just fine.
Solution 2:
I am not sure if that would work. I would recommend:
var p = newPromise(function (resolve, reject) {
$.getJSON('api/values', null)
.then(resolve, reject);
});
preferably you could create an adaptorfunction like:
var toPromise = function ($promise) {
returnnewPromise(function (resolve, reject) {
$promise.then(resolve, reject);
});
});
var p = toPromise($.getJSON('api/values', null));
Solution 3:
I would prefer composition:
constsuccessCb1 = ()=>$.getJSON('api/values'),
successCb2 = (json)=>alert(json),
errorCb = (e)=>alert(e);
Promise
.resolve()
.then(successCb1)
.then(successCb2)
.catch(errorCb);
Post a Comment for "How To Convert A Jquery Deferred Object To An Es6 Promise"