I am trying to make a post request via jQuery using an ES6 promise:
I have a function:
getPostPromise(something, anotherthing) {
return new Promise
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) {
// ...
});