Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to return an outer function inside an asynchronous inner function?

I know I can use an external variable to identify some status the outer function needs to do with. But consider this: If the inner function is asynchronous? The outer function will not wait for the variable of inner function will change, so how can I return the outer function now?

function outer() {
    var flag = true;
    // For example, a jquery-like ajax call
    $.ajax({
        // Some settings
        error: function(jqXHR, textStatus, errorThrown) {
            // Here I want to return outer()
            flag = false;
        }
    });
    return flag;
}

So as you can see, if I use flag as the return value, outer() will very likely return true because the ajax call may take a long time. And for the same reason, I don't want to set async: false because that will stop the page reaction.

like image 238
Melkor Avatar asked Apr 13 '14 11:04

Melkor


1 Answers

Your outer function will return immediately, so you will always get true as flag's value. In order to get the right value, you need to let the async function do its job and get back to you when it is ready. Consider this:

function outer(cb) {
    var flag = true;
    // For example, a jquery-like ajax call
    $.ajax({
        // Some settings
        error: function (jqXHR, textStatus, errorThrown) {
            // Here I want to return outer()
            flag = false;
            cb(flag);
        },
        success: function () {
            flag = true; // or whatever value you need.
            cb(flag);
        }
    });
}

function callback(flag) {
    // this function will be called after the ajax is complete.
    // real value of flag variable will be available here
    console.log(flag);
}
outer(callback);

You pass a function as a parameter to outer function, and it calls that function when ajax is complete with the value you need as a parameter. This way you will get the real result.

like image 122
keune Avatar answered Oct 20 '22 23:10

keune