es5中判断多个ajax全部执行完成后进行回调

Chydar 2019-07-01

$.when() jQuery中的api

$.when($.ajax({
    url: url,
    dataType: "jsonp",
    data: {"movieId": 248906},
    success: function(data) {
         var data = data.data.data;
        var actorList = data.stars.split(',').join(' | ');
        var type = data.category.split(',').join(' | ');  
        result.push({
            "actorList": actorList,
            "type": type
        })
    },
    error: function(err) {
        console.log(err)
    }
}), $.ajax({
    url: url,
    dataType: "jsonp",
    data: {"movieId": 1212492},
    success: function(data) {
         var data = data.data.data;
        var actorList = data.stars.split(',').join(' | ');
        var type = data.category.split(',').join(' | ');  
        result.push({
            "actorList": actorList,
            "type": type
        })
    },
    error: function(err) {
        console.log(err)
    }
}), $.ajax({
    url: url,
    dataType: "jsonp",
    data: {"movieId": 346765},
    success: function(data) {
         var data = data.data.data;
        var actorList = data.stars.split(',').join(' | ');
        var type = data.category.split(',').join(' | ');  
        result.push({
            "actorList": actorList,
            "type": type
        })
    },
    error: function(err) {
        console.log(err)
    }
})).done(function() {
    console.log(result)
})

全局变量判断

var ajax_done_count = 0;
function ajax_done() {
  if(ajax_done_count === 3) {
    // 渲染页面
  } else {
    // 什么都不做
  }
}

$.ajax({success: function(data) {
    ajax_done_count += 1;
    ajax_done();
}})
$.ajax({success: function(data) {
    ajax_done_count += 1;
    ajax_done();
}})
$.ajax({success: function(data) {
    ajax_done_count += 1;
    ajax_done();
}})

promise.all

貌似在es5中也支持promise了 ...

我写了一个demo

var url = 'http://xxx/xxx';
var idList = [248906, 1212492, 346765, 341139];
var result = [];
var promiseArr = [];

function createPromise (id) {
  return new Promise(function(resolve, reject) {
    $.ajax({
        url: url,
        dataType: "jsonp",
        data: {"movieId": id},
        success: function(data) {
            var data = data.data.data;
            resolve({
                "actorList": data.stars,
                "type": data.category
            });
        },
        error: function(err) {
            reject(err);
        }
    })
  })    
}

idList.map(function(i) {
    promiseArr.push(createPromise(i))
})

console.log(promiseArr)

Promise.all(promiseArr).then(function(data) {
    result = data;
    console.log(result);
    // 渲染页面
}).catch(function(err) {
    console.log(err);
})

相关推荐

mmywcoco / 0评论 2020-06-06