How to convert a jQuery Deferred object to an ES6 Promise

后端 未结 3 906
难免孤独
难免孤独 2020-12-28 13:28

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

var p = Promise.resolve($.getJSON(\'api/values\', null));

Are there any ot

3条回答
  •  太阳男子
    2020-12-28 14:00

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

提交回复
热议问题