Skip to content

Instantly share code, notes, and snippets.

@niraj-shah
Created October 8, 2018 16:18
Show Gist options
  • Select an option

  • Save niraj-shah/e508dd2d7db424fc7ecb6a652287efa1 to your computer and use it in GitHub Desktop.

Select an option

Save niraj-shah/e508dd2d7db424fc7ecb6a652287efa1 to your computer and use it in GitHub Desktop.

Revisions

  1. niraj-shah created this gist Oct 8, 2018.
    44 changes: 44 additions & 0 deletions sequential.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    // parameters for ajax calls
    var items = [
    { 'gender': 'male', 'nat': 'US' },
    { 'gender': 'female', 'nat': 'GB' }
    ];

    // function to trigger the ajax call
    var ajax_request = function(item) {
    var deferred = $.Deferred();

    $.ajax({
    url: 'https://randomuser.me/api/',
    dataType: "json",
    type: 'GET',
    data: item,
    success: function(data) {
    // do something here
    console.log(data.results[0]);
    // mark the ajax call as completed
    deferred.resolve(data);
    },
    error: function(error) {
    // mark the ajax call as failed
    deferred.reject(error);
    }
    });

    return deferred.promise();
    };

    var looper = $.Deferred().resolve();

    // go through each item and call the ajax function
    $.when.apply($, $.map(items, function(item, i) {
    looper = looper.then(function() {
    // trigger ajax call with item data
    return ajax_request(item);
    });

    return looper;
    })).then(function() {
    // run this after all ajax calls have completed
    console.log('Done!');
    });