0

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.

user8571142
  • 91
  • 2
  • 10

1 Answers1

2

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");
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • What does dodging jQuery promises mean? And if this is the way it is done in the docs why not follow it? – user8571142 Nov 20 '17 at 06:48
  • @user8571142 [`$.ajax` already returns a promise](http://api.jquery.com/jQuery.ajax/#jqXHR), but it's an instance of [jQuery's own promise implementation](http://api.jquery.com/category/deferred-object/) (which [is known to have its problems](https://stackoverflow.com/q/23744612/1048572)) not a native `Promise`. The MDN docs never use jQuery anywhere - `new Promise` is fine for asynchronous functions that take callbacks, such as `setTimeout`. – Bergi Nov 20 '17 at 06:54
  • @user8571142, if your code is in a function from which you wish to return a promise, then in all probability you need to `return promise.then(...)`, not the assigned intermediate `promise` variable. – Roamer-1888 Nov 20 '17 at 09:03