DragonWar% 2016-05-12 21:17 采纳率: 0%
浏览 39

奇怪的Javascript关闭错误

Here is some code.

function callServiceSync(url, obj) {
    var result = true;
    callServiceOptions(url, obj, function(res){
        result = res;
        alert("RESULT CB: "+JSON.stringify(result));
    }, {async: false});
    alert("RESULT POST-CB: "+JSON.stringify(result));
    return result;
}

When it runs, the alert box says:

RESULT CB: {"success":true,"data":"dtrombley"}

(that's what the webservice returns, in reality), and then:

RESULT POST-CB: true

Why isn't this assignment to the closure variable working? Am I misunderstanding how JS closures work?

callServiceOptions() is rather longwinded - but the gist of it is that it calls jQuery's $.ajax method with it's last arguments options extended into some default (in this case, async is disable for sync query), and then executes the provided callback.

Is $.ajax() maybe executing something in some kind of way that disables/screws up closures (but I call the cb, not $.ajax()!)? If so, how to fix that?

For completeness (though really this function shouldn't be able to screw things up to my thinking):

function callServiceOptions(url, obj, cb, options) {
    optSuccess = options.success;
    optError = options.error;
    opts = {}
    $.extend({},options)
    if (!opts.contentType) {
        opts.contentType = "application/json";
    }
    if (!opts.dataType) {
        opts.dataType = "json";
    }
    if (!opts.data && obj) {
        opts.data = JSON.stringify(obj);
    }
    if (!opts.processData) {
        opts.processData = false;
    }
    if (!opts.method) {
        opts.method = "POST";
    }
    opts.error = function(jqXHR, textStatus, errorThrown) {
        if (optError) {
            optError(jqXHR, textStatus, errorThrown);
        }
        if (jqXHR.responseText) {
            responseObj = JSON.parse(jqXHR.responseText)
            if (responseObj && responseObj.message)
            cb({
                success: false,
                message: responseObj.message
            })
            return
        }
        cb({
            success: false,
            message: errorThrown
        });
    };
    opts.success = function(data, textStatus, jqXHR) {
        if (optSuccess) {
            optSuccess(data,textStatus,jqXHR);
        } 
        cb(data);
    };
    if (url.charAt(0) == '/') {
        url = url.substr(1);
    }
    opts.url = WEBCTX.getBaseURL() + url;

    $.ajax(opts);
}

This is not a duplicate of any question asking how to return a value from an async event. I have a working callServiceAsync() which does that beautifully. I am using synchronous mode, if you aren't familiar with it, please take a pass on this question...

  • 写回答

1条回答 默认 最新

  • hurriedly% 2016-05-12 21:31
    关注

    Your function is asynchronous.

    While you have created an object that looks like {async: false}, you are passing it as the 4th argument to callServiceOptions so it gets placed in the options variable.

    You only access that variable twice (options.success and options.error) so the async property is never used for anything (so $.ajax uses the default value of true).

    Adding console.log(opts) just before you call $.ajax(opts); will show this.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀