Best practice for many AJAX API calls requiring a response from a previous call?

I am working on an internal page that allows the user to upload CSVs with resources and dates, and the page adds all the planning information for these resources to our management software. There's a pretty decent API for this, and I have a working model, but it seems ... cludgy.

For each resource, I have to start a new session, then create a new reservation, then add resources, and then confirm that the reservation is not blocked, and then send the order. Most calls return the variable that I need for the next step of the process, so everyone relies on the previous ajax call.

I am currently doing this through nested ajax calls like this:

$.ajax('startnewsession').then($.ajax('createreservation').then('etcetc'))

While this works, I feel that this requires a simpler or more “correct” way for both cleaner code and adaptation.

+4
source share
2 answers

What you are doing is right if you cannot change the API you are communicating with.

There really is no way to get around to making some kind of nested ajax calls if you need the previous response data for the next. Promises ( .then), however, make it a little more beautiful than making callbacks.

( ), , API , . , , API , .

ajax, , - API .

var baseApiUrl = 'https://jsonplaceholder.typicode.com';
$.ajax(baseApiUrl + '/posts/1')
  .then(function(post) {
    $.ajax(baseApiUrl + '/users/' + post.userId)
      .then(function(user) {
        console.log('got name: ' + user.name);
      }, function(error) {
        console.log('error when calling /users/', error)
      });
  }, function(error) {
    console.log('error when calling /posts/', error)
  });
0

: , :

ajaxCall1.then(
  response => ajaxCall2(response)
).then(
  response => ajaxCall3(response)
)

when. , ( ) 1 ajax ( ), 2 ajax-, , , , 0, . :

    function getGridData() {
      var count;
      callForRowsCount().then(
         (response) => {
            count = response;
            if(count > 0) {
              return callForData();
            } else {
              return [];
            }
         }
      ).then(response => {
         pub.fireEvent({
           type: 'grid-data',
           count: count,
           data: response
         })
      })
}

pub lisher, .

when. . , backend , ajax- . - :

var whenArray = [];
if(require1) {
  whenArray.push(ajaxCall1);
}
if(require2) {
  whenArray.push(ajaxCall2);
}
if(require3) {
  whenArray.push(ajaxCall3);
}
$.when.apply($, whenArray).then(() => loadMyData(arguments));
0

Source: https://habr.com/ru/post/1651805/


All Articles