Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

javascript - Promote callback onSuccess return value to the Caller Function return value

I have a javascript function that calls a generic function to make an ajax call to the server. I need to retrieve a result (true/false) from the callback function of the ajax call, but the result I get is always 'undefined'.

A super-simplified version of the generic function without all my logic would be:

function CallServer(urlController) {
    $.ajax({
        type: "POST",
        url: urlController,
        async: false,
        data: $("form").serialize(),
        success:
            function(result) {
                if (someLogic)
                   return true;
                else
                   return false;
            },
        error:
            function(errorThrown) {
                return false;
            }
    });
}

And the function calling it would be something like:

function Next() {
        var result = CallServer("/Signum/TrySave");
        if (result == true) {
            document.forms[0].submit();
        }
    }

The "result" variable is always 'undefined', and debugging it I can see that the "return true" line of the callback function is being executed.

Any ideas of why this is happening? How could I bubble the return value from the callback function to the CallServer function?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just in case you want to go the asynchronous way (which is a better solution because it will not freeze your browser while doing the request), here is the code:

function CallServer(urlController, callback) {
    $.ajax({
        type: "POST",
        url: urlController,
        async: true,
        data: $("form").serialize(),
        success:
            function(result) {
                var ret = ( someLogic );
                callback(ret);
            },
        error:
            function(errorThrown) {
                return false;
            }
    });
}

function Next() {
    CallServer("/Signum/TrySave", function(result) {
        if (result == true) {
            document.forms[0].submit();
        }
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...