$.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(); }})
貌似在es5中也支持promise了 ...
我寫了一個demojavascript
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); })