Ashe
Ashe

Reputation: 187

How to use javascript promises ES6 instead of jQuery ajax call?

I was trying to understand how promises works in javascript but I didn't found clear info about this, I would like to know if it possible and it is so how to do this using promises instead this code (equivalent)

$.ajax({
    type: 'post',
    cache: false,
    url: 'myfile.php',
    data: { info: info },
    datatype: 'json',

    success: function(response) {
        console.log(response);
    }
});

I ask this because I want to use only javascript without any framework or plugins, I have no problem with the other new feautures of ES6 just with this one, I hope you can help me, thanks.

Upvotes: 1

Views: 3524

Answers (2)

Faly
Faly

Reputation: 13356

You have to wrap your ajax call with a function that instantiates and returns a promise:

function getSomething() {
  return new Promise((resolve, reject) => {
    $.ajax({
        type: 'post',
        cache: false,
        url: 'myfile.php',
        data: { info: info },
        datatype: 'json',
        success: function(response) {
            resolve(response);
        },
        error: function() {
            reject("some errors");
        }
    });  
  });
}

Then you consume your promise like below:

getSomething()
    .then(response => console.log(response))
    .catch(err => console.log(err));

Upvotes: 1

You could do it like this

function doAjax() {
   return $.ajax({
        type: 'post',
        cache: false,
        url: 'myfile.php',
        data: { info: info },
        datatype: 'json',
    });
}
doAjax.then(function(data) {
    // do success stuff
}).fail(function() {
    // do fail stuff
});

Upvotes: 2

Related Questions