moyan's life

vuePress-theme-reco moyanfaker    2017 - 2021
moyan's life moyan's life

Choose mode

  • dark
  • auto
  • light
Home
Category
  • ES6
  • 闭包
  • js的未来
  • 数组
  • Typescript
  • 函数式编程
  • 防抖和节流
Tag
TimeLine
Docs
  • vuepress-reco
Contact
  • GitHub
author-avatar

moyanfaker

12

Article

12

Tag

Home
Category
  • ES6
  • 闭包
  • js的未来
  • 数组
  • Typescript
  • 函数式编程
  • 防抖和节流
Tag
TimeLine
Docs
  • vuepress-reco
Contact
  • GitHub

异步操作

vuePress-theme-reco moyanfaker    2017 - 2021

异步操作

moyanfaker 2020-12-11 模块化js

# 异步操作-ajax

# 异步操作:同时进行多个操作,用户体验好;代码混乱

# 同步操作:一次只能进行一个操作,用户体验不好;代码清晰

# //异步-麻烦

ajax(
  "http://taobao.com/api/user",
  function(data1) {
    ajax(
      "http:////taobao.com/api/items",
      function(data2) {
        ajax(
          "http://taobao.com/api/ad",
          function(data3) {},
          function() {
            alert("error");
          }
        );
      },
      function() {
        alert("error");
      }
    );
  },
  function() {
    alert("error");
  }
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# //同步-容易

let data1 = ajax("http://taobao/api/user");
let data2 = ajax("http://taobao/api/items");
let data3 = ajax("http://taobao/api/ad");
1
2
3

# 融合异步、同步

  • Promise
  • async/await
# Promise--封装
  • Promise.all([p1,p2,p3,...])
  • Promise.race 竞速
# 缺陷--无脑异步 不能判断
//同步
let user_data = ajax("http://taobao/api/user");
if (user_data.vip) {
  let data2 = ajax("http://taobao/api/items");
  let data3 = ajax("http://taobao/api/ad");
} else {
  let data2 = ajax("http://taobao/api/items");
  let data3 = ajax("http://taobao/api/ad");
}
//异步
ajax("http://taobao.com/api/user").then(
  (user_data) => {
    if (user_data.vip) {
      ajax("http://taobao.com/api/vip_items").then();
    }
  },
  (err) => {
    alert("失败");
  }
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# async/await
async function show() {
  xxx;
  xxx;

  let data = await $.ajax();
  xxx;
}

show();
1
2
3
4
5
6
7
8
9
  • 普通函数--一直执行 直到结束
  • async 函数---能够暂停