Architecture for Multiple API Calls Using jQuery and Javascript

Interestingly, others consider the best way for an architect to create an API call, which depends on the response of another API call in jQuery.

Steps:

  • Make JSONP API call endpoint, get response
  • If we get 200 successful responses from the first call, we will start another API call (JSON this time).
  • Print the results to the browser.

Here's how I could build it with rude error handling:

$(document).ready(function() {
  $.ajax({
     url: "http://example.com/json",
     type: 'POST',
     dataType: 'jsonp',
     timeout: 3000,
     success: function(data) {

       // Variables created from response
       var userLocation = data.loc;
       var userRegion = data.city;

       // Using variables for another call
       $.ajax({
         url: "http://example2.com/json?Location=" + userLocation + "&City=" + userRegion,
         type: 'POST',
         dataType: 'json',
         timeout: 3000,
         success: function(Response) {
          $(.target-div).html(Response.payload);
         },
         error: {
          alert("Your second API call blew it.");
         }
       });

     },
     error: function () {
       alert("Your first API call blew it.");
     }
  });
});
+4
source share
1 answer

Promise , ( ). . , .

https://www.promisejs.org/patterns/

http://api.jquery.com/jquery.ajax/

http://api.jquery.com/category/deferred-object/

  function displayPayload(response) {
    $(".target-div").html(response.payload);
  }

  function jsonpCall() {
    return $.ajax({
      url: "http://example.com/json",
      type: 'GET',
      dataType: 'jsonp',
      timeout: 3000
    });
  }

  function jsonCall(data) {
    // Variables created from response
    var userLocation = data.loc;
    var userRegion = data.city;

    // Using variables for another call
    return $.ajax({
      url: "http://example2.com/json?Location=" + userLocation + "&City=" + userRegion,
      type: 'GET',
      dataType: 'json',
      timeout: 3000
    });
  }

  $(document).ready(function() {
    jsonpCall()
      .done(function(data) {
        jsonCall(data)
          .done(function(response) {
            displayPayload(response);
          }).fail(function() {
            alert("Your second API call blew it.");
          });
      }).fail(function() {
        alert("Your first API call blew it.");
      });
  });
+4

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


All Articles