Are two asynchronous execution ends, re-synchronization is the third function

1.js method with 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)
})

If two sequentially performed, then the connection may be used, if the order is not required, can be placed in an array, execution 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请求均结束');
})

Guess you like

Origin blog.csdn.net/qwe435541908/article/details/81478423