简体   繁体   中英

Return result from nested asynchronous ajax call

I need to return the data from an nested ajax call but also need the ajax call to stay asynchronous.

I found some related questions but can't get it to work in the situation below. I assume returnData is being returned before the ajax call is done, but I can't find an solution.

function makeRequest(command, postData){

    var returnData;

    $.ajax({

        url: 'call.php?command='+command,
        data: postData,
        type: 'POST'

    }).done(function(data){
        returnData = data;
    });

    return returnData;
}

Yes since this call is async returnData is returned immediately. If you need to use returndata pass it to a function in the callback

function makeRequest(command, postData, functionToCallAfterAjax){

    var returnData;

    $.ajax({

        url: 'call.php?command='+command,
        data: postData,
        type: 'POST'

    }).done(function(data){
        functionToCallAfterAjax(data);
    });


}

Of course you could pass the function to call as a parameter.

This means that if your code was meant to do:

var returnedData = makeRequest(command, postData);
anotherFunction(returnedData);

you should do simply (using the code above)

makeRequest(command, postData, anotherFunction);

and everything will work

You can't. Asynchronous events don't work like that.

The HTTP request is sent, then the function that triggers it continues immediately . The callback won't be fired until the HTTP response has arrived, but which time the calling function will have ended.

You must have your callback (the function you are passing to done() ) perform whatever further processing is needed.

You're returning the value of returnData before the .done() function has run. Correct your code by passing the received data to a function for processing:

function makeRequest(command, postData){
    $.ajax({
        url: 'call.php?command='+command,
        data: postData,
        type: 'POST'
    }).done(function(data){
        HandleCallBack(data);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM