ajax 界面无then

ajax interface without then

我想将 ajax 调用打包到没有 then 的接口中。

如果我这样做,它只会 return 'No ajax return';

var ajaxReturn = ajaxFunction();
function ajaxFunction(){
    var text = 'No ajax return';
    // get fileName using an ajax get
    $.ajax();
    return text;
}

如果我这样做,那么使用起来会很难看;

function ajaxFunction(){
    var text = 'No ajax';
    var dtd = $.Deferred();
    $.ajax();
    return dtd.promise();
}

$.when(ajaxFunction()).then();

我只希望界面简单 return 正确,可以吗?

//return the right
var ajaxReturn = ajaxFunction();

嗯...,ajax 是异步的,因此您可以使用 .then() 或使用 回调 逻辑...做同步ajax对我来说不是一个选项,所以我什至不会提到它。

.then() 的替代方法是这样的:

ajaxFunction(function(res){ // pass a function into it
    // this will be called when the ajax is done
    alert(res);
});
function ajaxFunction(callback){
    // get fileName using an ajax get
    $.ajax({
        success: callback
    });
}

但同样,也许您可​​以只使用普通的 ajax 回调模式

$.ajax({
    ...
    success: function(res){
        // use the res
    }
});

Ajax 是异步的。 then 旨在使编写异步操作看起来更类似于同步代码,实际上可以非常优雅。

另外,$.ajax()returns一个promise,很适合这样写:

function ajaxFunction(){
    return $.ajax();
}

ajaxFunction().then(function(response){
    // do whatever you want with the response
})

您根本无法以这种方式编写异步代码 (ajaxResult = ajaxFunction())。解释器将继续逐行传输,ajaxResult 将无法及时准备好。

继续阅读 $.Deferred 的链接。它将真正清理您的异步代码。

function ajaxFunction(){
    var text = 'No ajax';
    var dtd = $.Deferred();
    $.ajax();
    return dtd.promise();
}

$.when(ajaxFunction()).then();

哇,那是什么?你确实需要 .then 但你不需要周围的大部分东西。 $.ajax 为您生成承诺。您不需要自己创建一个 promise 对象。事实上,通常您需要直接手动设置 Deferred/Promise 的唯一原因是您正在使用一些设置回调的库并且不使用 promises 本身。

function ajaxFunction(){
    return $.ajax();
}

ajaxFunction().then(function(data) { ... });

现在,假设您实际上不想 return JSON 函数末尾的 JSON 结构;您只想从其中取出一个数字,或者调整一个值以使其成为调用者更易于使用的函数。足够简单:

function ajaxFunction(){
    return $.ajax().then(function(data) {
      return data[12].number;
    }
}

ajaxFunction().then(function(number) { ... });

直接回答你的问题:不,你所要求的是不可能的。每当您的 JavaScript 方法是 运行 时,浏览器就无法处理其他事件,例如点击甚至基本的滚动操作。因此,任何长 运行 操作(如联系服务器)不会立即 return,而是提供回调操作。