首页 > 求jquery中更好的写法。

求jquery中更好的写法。

假如我现在有5个ajax要调取,现在实现的效果是相继调取,即第一个ajax done后执行第二个ajax,以此类推。

我能想到的就是放在回调里了,但是觉得这样不优雅,也不容易维护。求大神指点。


上面说的都很好,promise.all不支持串行调用,上面的给出了一个解决方法,但是如果需要穿行的更多,那个链式的调用岂不是很长?

第一位给的链接很好,以前也用过(图片上传一个接一个的传),贴一下代码:

function getURL(URL) {
    return new Promise(function (resolve, reject) {
        var req = new XMLHttpRequest();
        req.open('GET', URL, true);
        req.onload = function () {
            if (req.status === 200) {
                resolve(req.responseText);
            } else {
                reject(new Error(req.statusText));
            }
        };
        req.onerror = function () {
            reject(new Error(req.statusText));
        };
        req.send();
    });
}
var request = {
        comment: function getComment() {
            return getURL('http://azu.github.io/promises-book/json/comment.json').then(JSON.parse);
        },
        people: function getPeople() {
            return getURL('http://azu.github.io/promises-book/json/people.json').then(JSON.parse);
        }
    };
function main() {
    function recordValue(results, value) {
        results.push(value);
        return results;
    }
    var pushValue = recordValue.bind(null, []);
    var tasks = [request.comment, request.people];
    return tasks.reduce(function (promise, task) {
        return promise.then(task).then(pushValue);
    }, Promise.resolve());
}
// 运行示例
main().then(function (value) {
    console.log(value);
}).catch(function(error){
    console.error(error);
});

https://.com/q/1010000003919398 我提过差不多的问题。你可以看看


Promise.all中所有promise对象全部变为resolve或reject状态的时候,它才会去调用 .then 方法,并不能保证5个ajax被串行调用。不过使用Promise的思路是对的。
下面是我的代码,ajax call返回一个promise对象,then方法会在promise变成reject或resolve状态后被调用,如果其返回值为另一个promise对象(ajax call)的话,第二个then方法将在新ajax call完成后被调用,从而保证了串行。

$.get("https://.com/q/1010000004579898", function(){
  console.log("invoked 1");
}).then(function(){
  return $.get("https://.com/q/1010000004579898", function(){
    console.log("invoked 2");
  })
}).then(function(){
  return $.get("https://.com/q/1010000004579898", function(){
    console.log("invoked 3");
  })
})

var http = $.ajax('demo.html');
var http1 = $.ajax('demo1.html');
var http2 = $.ajax('demo2.html');

http
        .success(function (res) {
            return http1;
        })
        .success(function (res1) {
            return http2;
        })
        .success(function (res2) {
            console.log(res2);
        })

async: false ; ajax 默认异步加载,设置属性同步加载后 直接按顺序执行function 不用放在回调函数中


jQuery的ajax请求都返回Promise对象的,你的需求可以使用Promise中的链式调用

【热门文章】
【热门文章】