jQuery ajax with ES6 Promises

前端 未结 1 683
南笙
南笙 2020-12-23 21:11

I am trying to make a post request via jQuery using an ES6 promise:

I have a function:

getPostPromise(something, anotherthing) {
  return new Promise         


        
相关标签:
1条回答
  • 2020-12-23 21:41

    jQuery Ajax methods return promises themselves, you don't need to wrap them at all.

    But you can, of course, do it for consistency with the ES6 promise API.

    UPDATE jQuery 3.0+ implements the Promise/A+ API, so there is no reason anymore to wrap anything in modern jQuery. Read up on the peculiarities of jQuery's promise implementation prior to version 3.0.

    For jQuery versions before 3.0, I would decouple it more than you did:

    function ajax(options) {
      return new Promise(function (resolve, reject) {
        $.ajax(options).done(resolve).fail(reject);
      });
    }
    

    and

    ajax({
      url: someURL,
      type: 'post',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify({
        something: something,
        anotherthing: anotherthing
      })
    }).then(
      function fulfillHandler(data) {
        // ...
      },
      function rejectHandler(jqXHR, textStatus, errorThrown) {
        // ...
      }
    ).catch(function errorHandler(error) {
      // ...
    });
    
    0 讨论(0)
提交回复
热议问题