2

I have an ajax request and I need to wait for the response to come back. I'm sure I have to use promises, but I'm really scared of promises and I can never understand it. It has multiple things named .then(), .resolved(), .reject(), .catch() etc. which makes me confused.

I have to use it anyway. So here is my code which doesn't work:

Promise(function (resolve, reject) {
    var req = $.ajax({
        url: path,
        type: 'GET',
        data: {"name": value },

        beforeSend: function () {
            if (req != null) {
                req.abort();
            }
        },
        success: function (url) {
            resolve(url);
        },

        error: function (jqXHR, textStatus, errorThrown) {
            reject(textStatus);

        },

        timeout: 20000

    });
});

As far as I know, that an ajax call happens, because when I put console.log(url) in success block, it prints the url as well and all fine. But I don't know how can I return it? I mean how resolve() returns something? And when exactly should I use .then()?

iiRosie1
  • 162
  • 2
  • 17
stack
  • 10,280
  • 19
  • 65
  • 117
  • @Adriani6 Nope, I've used promises once .. – stack Dec 24 '17 at 15:18
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Serge K. Dec 24 '17 at 15:18

3 Answers3

2

Promise should be used like this :

var promise1 = new Promise(function(resolve,reject){

    $.ajax({
       url : 'yourUrls',
       success : function(data){
         resolve(data);
       },
       error : function(err) {
          reject(err);
       }
    })
});

promise1.then(function(response){
   //response is what you resolve in promise
}).catch(function(err){
   //err is what you send while you reject inside promise
});
Pradeep
  • 140
  • 9
  • 3
    side note for jQuery >= 3, you don't have to wrap the function to Promise constructor anymore since it's already a Promises/A+ compatible – Chay22 Dec 24 '17 at 15:25
  • Oh okay. Thanks buddy. I dint know this. I follow MDN website. Docs there still has function passed to the constructor. – Pradeep Dec 24 '17 at 15:34
2

BTW, $.ajax returns jqXHR object that implements the Promise interface, giving them all the properties, methods, and behavior of a Promise. So your code can look like this

function onResolve () { alert( "$.ajax succeeded" ); }
function onReject () { alert( "$.ajax failed" ); }

// Promise syntax style
$.ajax({ 
    url: path,
    type: 'GET',
    data: {"name": "value"}
}).then(onResolve, onReject);

// or equivalent jQuery syntax style
$.ajax({
    url: path,
    type: 'GET',
    data: {"name": "value"},
    success: onResolve, 
    error: onReject
});
tetta
  • 445
  • 4
  • 17
  • Where is `beforeSend`, `success`, `error`, `timeout` in your ajax call? Also you have two anonymous functions into `.then()`, how do you know the first one is for success and the second one is for being fail? I mean shouldn't you set `resolve` and `reject` for them? – stack Dec 25 '17 at 05:51
  • As I see you don't need `beforeSend`, `timeout` parameters. `then` will be used instead of `success`, `error`. it's more about organizing code. No matter how you resolve/reject it. can do it this way `$.ajax().then(resolve, reject)` or like this `$.ajax({success: resolve, error: reject})`. It's equivalent notations – tetta Dec 25 '17 at 08:20
  • Thank you, upvote .. Just please add those two syntax you mentioned in your comment to your answer. I like to see how exactly `resolve` and `reject` should be used. – stack Dec 25 '17 at 09:35
1

You can return New Promise like :

 function ajaxDone() {
    return new Promise(function (resolve, reject) {
       $.ajax({
               url: path,
               type: 'GET',
               data: {"name": value },
               beforeSend: function () {
                  if (req != null) {
                       req.abort();
                        }
                    },
              success: function (url) {
                    resolve(url);
                       },
              error: function (jqXHR, textStatus, errorThrown) {
                     resolve(null);
                 },

              timeout: 20000
             });
    });
}

and how you can use:

    ajaxDone().then(function (resolve) {
            if (resolve !== null && resolve !== undefined)
              //It is done
             else
               //not done
 });
Aria
  • 3,724
  • 1
  • 20
  • 51