异步处理

由于 XHR 是一个异步的机制,在处理请求的时候,需要等待服务端返回才能拿到数据。有时候我们需要从服务端返回拿到数据,再用这个数据去请求服务端,再用返回的数据去处理其他逻辑。当嵌套够深的时候,就会陷入一个 callbackhell(回调地狱)。在处理异步事件中,主要有以下几种方法:

  • callback
  • Promise
  • async/await

在此我们统一用 setTimeout 来模拟 xhr 的异步数据返回。

callback

const xhr1 = function(cb){
  setTimeout(()=>{
    const data = 1;
    typeof cb === 'function' && cb(data)
  },2000)
}

const xhr2 = function(cb){
  setTimeout(()=>{
    const data = 2;
    typeof cb === 'function' && cb(data)
  },2000)
}

const xhr3 = function(cb){
  setTimeout(()=>{
    const data = 3;
    typeof cb === 'function' && cb(data)
  },2000)
}

// 执行
xhr1((data1)=>{
  console.log(data1)
  xhr2((data2)=>{
    console.log(data2)
    xhr3((data3)=>{
      console.log(data3)
    })
  })
})

Promise

const xhr1 = function(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      const data = 1;
      resolve(data)
    },2000)
  })
}

const xhr2 = function(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      const data = 2;
      resolve(data)
    },2000)
  })
}

const xhr3 = function(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      const data = 3;
      resolve(data)
    },2000)
  })
}

// 执行
xhr1().then((data1)=>{
  console.log(data1);
  return xhr2();
}).then((data2)=>{
  console.log(data2);
  return xhr3();
}).then((data3)=>{
  console.log(data3)
}).catch( e => {
  console.log(e)
})

// 并行执行
Promise.all([xhr1(),xhr2(),xhr3()]).then((data)=>{
  console.log(data)
}).catch( e => {
  console.log(e)
})

async

const xhr1 = function(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      const data = 1;
      resolve(data)
    },2000)
  })
}

const xhr2 = function(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      const data = 2;
      resolve(data)
    },2000)
  })
}

const xhr3 = function(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      const data = 3;
      resolve(data)
    },2000)
  })
}

async function xhr(){
  const data1 = await xhr1();
  console.log(data1);
  const data2 = await xhr2();
  console.log(data2);
  const data3 = await xhr3();
  console.log(data1,data2,data3);
}

xhr();