美文网首页我爱编程
多个ajax请求后的返回操作

多个ajax请求后的返回操作

作者: SailingBytes | 来源:发表于2018-05-25 10:28 被阅读0次

1、async

jquery ajax默认异步请求,但可以在请求添加  async: false ,这样就会同步执行,请求的顺序就是代码的顺序。

2、$.when()

提供一种基于零个或多个Thenable对象执行回调函数的方法。

如果没有参数传递给$.when(),他讲返回一个已解析的 Promise。

var ajax1 = $.ajax({ url: "/ajax1.php", type:"post", data:{}, dataType: "json" });

var ajax2 = $.ajax( "/ajax2.php" );

$.when( ajax1, ajax2 ).done(function () {

    // 执行操作

});

3、promise

(1)重复 then

function a () {

    return new Promise (function(resolve, reject) {

        resolve('执行任务a成功');

    });

}

function b () {

    return new Promise (function(resolve, reject) {

        resolve('执行任务b成功');

    });

}

a().then(b())

(2) promise.all

将多个 Promise 实例,包装成一个新的 Promise 实例。

ES6,需要首先判断 window.promise 是否具备。

Promise.all([

    ajax1,

    ajax2

]).then(() => {

    // 执行操作

}).catch(()=> {});

相关文章

网友评论

    本文标题:多个ajax请求后的返回操作

    本文链接:https://www.haomeiwen.com/subject/qjryjftx.html