如何将jQuery递延对象转换为ES6承诺

时间:2022-08-23 11:54:43

Is this the correct way to convert jQuery Deferred to a Promise?

这是转换jQuery的正确方式吗?

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?

局限性是什么?我曾经读到过jQuery deferred不支持异常,所以我假设从deferred中创建的承诺也不支持。这是正确的吗?

3 个解决方案

#1


7  

Yes it should, the Promise.resolve() API supports thenable as argument. So passing a jquery defer object would work just fine.

是的,应该这样,promisee .resolve() API支持将其作为参数。因此,通过一个jquery延迟对象可以很好地工作。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve#Resolving_thenables_and_throwing_Errors

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve Resolving_thenables_and_throwing_Errors

#2


8  

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:

最好您可以创建一个adaptorfunction,比如:

var toPromise = function ($promise) {
  return new Promise(function (resolve, reject) {
    $promise.then(resolve, reject);
  });
});

var p = toPromise($.getJSON('api/values', null));

#3


2  

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

#1


7  

Yes it should, the Promise.resolve() API supports thenable as argument. So passing a jquery defer object would work just fine.

是的,应该这样,promisee .resolve() API支持将其作为参数。因此,通过一个jquery延迟对象可以很好地工作。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve#Resolving_thenables_and_throwing_Errors

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve Resolving_thenables_and_throwing_Errors

#2


8  

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:

最好您可以创建一个adaptorfunction,比如:

var toPromise = function ($promise) {
  return new Promise(function (resolve, reject) {
    $promise.then(resolve, reject);
  });
});

var p = toPromise($.getJSON('api/values', null));

#3


2  

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