javascript - 从嵌套回调函数中提取返回值

标签 javascript jquery ajax callback

为了简化我的问题,我对代码做了一些修改。我现在可以从回调函数中获取值,我现在想将此数据传递到变量中。

Javascript

如何让 PostInformation 返回参数?

function AjaxRequest(callback) {

    var hasErrors = false;
    dojo.xhrPost({
        url: 'hello',
        content: SomeData,
        load: function (formErrors) {
            //preform some operation 
            //set hasErrors to true
            hasErrors = true;

            if (typeof callback === "function") callback(hasErrors);
        },
        error: function (e) {
            console.log(e + ' page not posted error');

        }

    });
}

function PostInformation() {
    try {
        AjaxRequest(function (args) {
            console.log('The hasErrors is  ' + args);
            return args;
        });

    } catch (e) {
        console.log(e);
    }
}

最佳答案

您在发送请求时调用 handleServerResponse,而不是在回调中。应该是:

var doesErrorsExist = postToServer(function() {
    handleServerResponse(containers, function (args) {
        return args;
    });
});

但这仍然行不通——异步函数永远无法向其调用者返回值,因为在函数返回后操作完成之前该值不会存在。

我没有试图弄清楚你想做的所有事情的逻辑,所以我没有关于如何解决这个问题的具体建议。我认为如果您重读链接到的问题,您应该会获得更多见解。

关于javascript - 从嵌套回调函数中提取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23226215/

相关文章:

javascript - 重新调整有效 JSON 时调用的 Ajax 错误回调

javascript - 如何访问在 php 标签内创建的文本框值以进行 ajax 调用

javascript - 录音javascript

jquery - 如何使用highchart整合市场深度图?

.net - 日期时间的自定义 JavaScriptConverter?

javascript - 在循环中执行 ajax 查询,然后执行使用其组合输出的函数

javascript - 无法通过ajax在jquery fullcalendar中设置动态数据

javascript - 如何在 Linux 操作系统上使用 javaScript、html(执行按钮)、node.js 和 firefox 浏览器执行 Linux shell 命令或脚本?

javascript - 在 iOS Safari 上借助 getUsermedia 访问麦克风

javascript - 如何使此代码更有用(防止文本区域中出现特殊字符)