Search code examples
javascriptajaxasynchronouspromisees6-promise

Uncaught in promise error but getting result from first call


I have two AJAX calls, the second one depends on the first one, so I decided to use promises. I keep getting Uncaught (in promise) abc123 error in console. Note that abc123 is the id I am expecting from the first AJAX call. The second AJAX call never goes inside success function.

var promise = new Promise(function(reject, resolve) {
  $.ajax({
    url: url1, 
    dataType: 'json',
    success: function (obj1) {
      console.log("Got obj1");
      resolve(obj1.id);
    }
  });
});

promise.then((id)=> {
  $.ajax({
    url: url2, 
    dataType: 'json',
    success: function (obj2) {
      console.log("Got obj2");
    }
  });
});

The structure looks exactly the same as Basic Example. I am really confused about what I am doing wrong.


Solution

  • You mixed up the order of the callback functions: resolve is the first argument, reject is the second, so you when you called the second one (resolve(obj.id)) you actually rejected your promise.

    However, notice that you should not use the Promise constructor anyway when dodging jQuery promises - just use Promise.resolve to cast the jQuery promise that $.ajax returns to a native one:

    var promise = Promise.resolve($.ajax({
      url: url1, 
      dataType: 'json'
    })).then(obj1 => {
      console.log("Got obj1");
      return obj1.id;
    });
    
    promise.then(id => {
      return $.ajax({
    //^^^^^^ don't forget this
        url: url2, 
        dataType: 'json'
      });
    }).then(obj2 => {
      console.log("Got obj2");
    });