1.js用Promise方法
// 封装地形 GeoJSON 数据接口
// 将每个数据接口封装为一个返回 Promise 的函数
function getArea () {
return new Promise((resolve, reject) => {
fetch('./resources/china.json').then(resp =>
resp.json().then(china => resolve(china))
)
})
}
// 封装分色地图数据接口
function getPopulation () {
return new Promise((resolve, reject) => {
fetch('./resources/china-population.json').then(resp =>
resp.json().then(data => resolve(data))
)
})
}
// 封装城市数据接口
function getCity () {
return new Promise((resolve, reject) => {
fetch('./resources/city.json').then(resp =>
resp.json().then(data => resolve(data))
)
})
}
// 使用 Promise.all 以在三个数据接口均异步成功后,执行回调逻辑
Promise.all([getArea(), getPopulation(), getCity()]).then(values => {
// 依次从返回的数据接口数组中获取不同接口数据
let china = values[0]
let population = values[1]
let city = values[2]
// 使用数据
doWithData(china, population, city)
})
如果需要两个依次执行,可以用then连接,如果对顺序无要求,可以放入一个数组中,用Promise.all执行。
2.jquery用$.when
$.when($.ajax({
url: "test1.html",
data:data1,
}),$.ajax({
url: "test2.html",
data:data2,
})).done(function(){
console.log('2个ajax请求均结束');
}).fail(function(){
console.log('2个ajax有请求失败');
})
$.when($.ajax({
url: "test1.html",
data:data1,
}, $.ajax({
url: "test2.html",
data:data2,
})).then(function(data1,data2){
console.log('2个ajax请求均结束');
})