async和promise都是处理异步请求的,那么选用哪个更好呢

与世无争的帅哥 提交于 2020-02-28 07:04:06

js 异步回调Async/Await与Promise的区别

官网讲解更完善哦

  • 一、Promise

import http from '....';
// promise方法1
function getData1() {
  return new Promise((resolve,reject) => {
    http.get('getData1', callback => {
      console.log(callback);
      resolve("success")
    }, error => {
      resolve("error");
    })
  })
}

function getData2() {
  return new Promise((resolve,reject) => {
    http.get('getData2', callback => {
      console.log(callback);
      resolve("success")
    }, error => {
      resolve("error");
    })
  })
}

// 获取两个异步请求的数据

// Promise-1
let value1 = getData1().then(res=>{
  if (res === 'success'){
    getData2().then(rs=>{
      if(rs==='success'){
        console.log()
      }
    })
  }
});
  • Promise.all
// promise 方法二
let value2 = function () {
  return Promise.all([
    http.get('getData1'),
    http.get('getData2'),
  ]).then ( res => {
    console.log(res[1]);
    console.log(res[2]);
  },error=>{
    console.log(error);
  })
};
// Promise-2
value2().then(()=>{
  console.log("complete")
});

  • 二、async
// async方法实现
let asyncValue = async () => {
  await http.get('getData1', res => {
    console.log(res);
  });
  await http.get('getData2', res => {
    console.log(res);
  })
  console.log("complete")
}

// async 相比较promise而言,更加简洁干净, 看起来像同步代码;
完全避免了层层嵌套的可能。
// 处理错误代码更加简单
const makeRequest = async () => {
  try {
    // this parse may fail
    const data = JSON.parse(await getJSON());
    console.log(data)
  }
  catch (err) {
    console.log(err)
  }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!