原生ajax

  1. //创建异步对象
  2. var xhr = new XMLHttpRequest();
  3. //设置请求基本信息,并加上请求头
  4. xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  5. xhr.open('post', 'test.php' );
  6. //发送请求
  7. xhr.send('name=Lan&age=18');
  8. xhr.onreadystatechange = function () {
  9. // 这步为判断服务器是否正确响应
  10. if (xhr.readyState == 4 && xhr.status == 200) {
  11. console.log(xhr.responseText);
  12. }
  13. };

jqueryAjax

  1. var loginBtn = document.getElementsByTagName("button")[0];
  2. loginBtn.onclick = function(){
  3. ajax({
  4. type:"post",
  5. url:"test.php",
  6. data:"name=lan&pwd=123456",
  7. success:function(data){
  8. console.log(data);
  9. }
  10. });
  11. }

fetch

  1. fetch('http://www.mozotech.cn/bangbang/index/user/login', {
  2. method: 'post',
  3. headers: {
  4. 'Content-Type': 'application/x-www-form-urlencoded'
  5. },
  6. body: new URLSearchParams([
  7. ["username", "Lan"],["password", "123456"]
  8. ]).toString()
  9. })
  10. .then(res => {
  11. console.log(res);
  12. return res.text();
  13. })
  14. .then(data => {
  15. console.log(data);
  16. })

Axios

  1. axios({
  2. method: 'post',
  3. url: '/abc/login',
  4. data: {
  5. userName: 'Lan',
  6. password: '123'
  7. }
  8. })
  9. .then(function (response) {
  10. console.log(response);
  11. })
  12. .catch(function (error) {
  13. console.log(error);
  14. });

async await

promise 的链式调用

  1. async function testAsync() {
  2. return "hello async";
  3. }
  4. const result = testAsync();
  5. console.log(result); // Promise { 'hello async' }

根据上面的代码结果可以看出async返回的是Promise对象。如果函数返回值是一个直接量,async函数会通过Promise.resolve()封装成Promise对象。
image.png
由于是Promise对象,我们只能通过then的链式调用来获取内部结果。而await用于等待async的返回结果,即Promise的最终结果。

  • 如果await等到的不是一个Promise对象,那么await表达式等到的就是他的结果
  • 如果await等到的是一个Promise对象,await会阻塞后面的代码,等待Promise的resolve结果,然后得到resolve的值,作为await的运算结果

    await的优势在于处理then的链式调用

  1. /**
  2. * 传入参数n, 表示这个函数执行时间(毫秒)
  3. * 执行结果是n+200,这个值用于下一步骤
  4. */
  5. function takeLongTimeUsingChain(n) {
  6. return new Promise(resolve => {
  7. setTimeout(() => resolve(n + 200), 1000);
  8. });
  9. };
  10. function step1(n) {
  11. console.log(`step1 with ${n}`);
  12. return takeLongTimeUsingChain(n);
  13. }
  14. function step2(n) {
  15. console.log(`step2 with ${n}`);
  16. return takeLongTimeUsingChain(n);
  17. }
  18. function step3(n) {
  19. console.log(`step3 with ${n}`);
  20. return takeLongTimeUsingChain(n);
  21. }

如果使用Promise的then链式调用来实现:

  1. function doIt() {
  2. console.log("doIt");
  3. const time1 = 300;
  4. step1(time1)
  5. .then(time2 => step1(time2))
  6. .then(time3 => step2(time3))
  7. .then(result=> {
  8. console.log(`result is ${result}`)
  9. console.log("doIt");
  10. })
  11. }

如果使用await方法:

  1. async function doIt() {
  2. console.log("doit begin");
  3. const timer1 = 300;
  4. const timer2 = await step1(timer1);
  5. const timer3 = await step2(timer2);
  6. const result = await step3(timer3);
  7. console.log(`result is ${result}`);
  8. console.log("doit end");
  9. }

obvervable ….待完成