Q:

How to execute the method until every Ajax method get data

I have a log method which need to execute until ajax method: getUserIP  get the value.
getUserIP will be run in $document.ready() method, and in its success method,it will run another ajax method called getsas method.
code like this:
 var userIP,sasToken,isReady;
$(document).ready(function ( ) { 
  getUserIP();
});

function getUserIP() {
    if (!userIP) {
        $.ajax({
            type: "GET",
            url: "http://jsonip.com?callback=?",
            dataType: "jsonp",
            jsonp: "callback",
            jsonCallback: "jsonCallBack",
            success: function (data) {
                callback(data);
                getSASEveryMinute();
            }
        });
    }
}
//Handle the response data from jsonip and SASTokenService.svc
//save them in globle varible 
function callback(data) {
    if (data.ip)
        userIP = data.ip
    else {
        sasToken = data.sasToken;
        isReady = true;
    }
}
function getSASEveryMinute() {
    url = "http://asdfasdf/TokenService.svc/json/Logs/" + userIP;
    getSAS();
    function getSAS() {
        $.ajax({
            url: url,
            type: 'GET',
            dataType: "jsonp",
            jsonp: "callback",
            jsonpCallback: "jsonCallback",
            success: function (data) {
                callback(data);

            }
        });
    }
    setInterval(function () {
        getSAS();
    }, 60000);
}

 function insertEntity(entity) {
        if (isReady) {
            entity.PartitionKey = userIP;
            insert(entity);       
        }
        else {
            setTimeout(function () { insertEntity(entity) }, 2000);
        }

Do we have a better way then 
 setTimeout(function () { insertEntity(entity) }, 2000);

Thanks a lot!

A:

First, separate out your AJAX calls into functions that do nothing except place a single AJAX request, and then return the jqXHR value:
function getUserIp() {
    return $.ajax(...).then(function(data) {
        return data.ip;
    });
}

function getSAS(userIp) {
     return $.ajax(...);
}

Note the use of .then to "filter" the return value from the first AJAX call so that it only returns the desired IP address, and not the whole data structure.
You'll then need a function that tries to get the SAS token once per minute, but doesn't "resolve" the promise until it has it:
function getSASRepeatedly(userIp) {
    var def = $.Deferred();

    (function loop() {
        getSAS(userIp).done(function(data) {
           if (data.sasToken) {
               def.resolve(userIp, data.sasToken);
           } 
           setTimeout(loop, 60000);  // do it again
        });
    )();

    return def.promise();
}

Then you can use .then and .done to chain it all together:
getUserIp().then(getSASRepeatedly).done(function(ip, token) {
    // do your insert here
});

