What's the difference between Promise and AJAX? What's the difference between Promise and AJAX? ajax ajax

What's the difference between Promise and AJAX?


You are confused about promises and Ajax calls. They are kind of like apples and knives. You can cut an apple with knife and the knife is a tool that can be applied to an apple, but the two are very different things.

Promises are a tool for managing asynchronous operations. They keep track of when asynchronous operations complete and what their results are and let you coordinate that completion and those results (including error conditions) with other code or other asynchronous operations. They aren't actually asynchronous operations in themselves. An Ajax call is a specific asynchronous operation that can be used with with a traditional callback interface or wrapped in a promise interface.

So what's the difference between them? And when would be best to use one instead of the other?

An Ajax call is a specific type of asynchronous operation. You can make an Ajax call either with a traditional callback using the XMLHttpRequest interface or you can make an Ajax call (in modern browsers), using a promise with the fetch() interface.

Recently I encountered a promise which had an AJAX in its body. Why put an async operation inside an async operation? That's like putting a bread loaf in a bread sandwich.

You didn't show the specific code you were talking about, but sometimes you want to start async operation 1 and then when that async operation is done, you want to them start async operation 2 (often using the results of the first one). In that case, you will typically nest one inside the other.


Your code example here:

function threadsGet() {    return new Promise((resolve, reject) => {      $.getJSON('api/threads')        .done(resolve)        .fail(reject);      })}

is considered a promise anti-pattern. There's no reason to create a new promise here because $.getJSON() already returns a promise which you can return. You can just do this instead:

function threadsGet() {    return $.getJSON('api/threads');}

Or, if you want to "cast" the somewhat non-standard jQuery promise to a standard promise, you can do this:

function threadsGet() {    return Promise.resolve($.getJSON('api/threads'));}