JS 异步请求多层嵌套解决⽅案-Promise 对象的使⽤
对象
Promise是中对于原⽣异步操作的解决⽅案,为异步操作提供统⼀的接⼝,可以让异步操作代码写起来像写同步操作的流程的代码⼀样,不⽤⼀层层的去嵌套
1.对象的状态
1.异步操作未完成 - pending
2.异步操作已完成 - fulfilled
3.异步操作失败 - rejected
三个状态⾥⾯,fulfilled与rejected合在⼀起称为已定型(resolved)
这三种状态的的变化途径只有两种
1.未完成->成功 Promise返回⼀个value,状态为fulfilled
2.未完成->失败 Promise抛出⼀个error,状态为rejected
⼀旦状态发⽣变化就不会再出现其他的状态的变化,⼀个Promise实例的状态变化只可能出现⼀次,最终结果只有两种
2.Promise 的使⽤// 传统写法step1(function  (value1) {//异步代码1  step2(value1, function (value2) {  //异步代码2    step3(value2, function (value3) {    //异步代码3      step4(value3, function (value4) {        //异步代码4      });    });  });});// Promise 的写法var  p1 = new  Promise (step1).then (step1).then (step2).then (step3).then (step4)Promise 的设计是所有的异步任务都返回⼀个Promise 实例,实例的then 就是⽤来指定下⼀步的回调函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23new  Promise (function  (resolve , reject ) {    console .log ("Run");});resolve 和reject 都是回调函数,resolve 代表⼀切正常,reject 出现异常时调⽤的 ----------------------------------------------------------------------------------------------------------使⽤1var  myPromise = new  Promise (function (resolve , reject ){    //当异步代码执⾏成功时,我们才会调⽤resolve(...), 当异步代码失败时就会调⽤reject(...)  $.get ('/demo',{data :'test'},res =>{  resolve ("成功!"); //代码正常执⾏!
1
2
3
4
5
6
7
8
9
10
11
resolve ("成功!"); //代码正常执⾏!  },'json');});myPromise .then (function (msg ){    //msg 的值是上⾯调⽤resolve(...)⽅法传⼊的值.    //msg 参数不⼀定⾮要是字符串类型,这⾥只是举个例⼦    console .log ("Yay! " + msg );});----------------------------------------------------------------------------------------------------------使⽤2:处理Promise 返回的异常var  msg = new  Promise (function  (resolve , reject ) {    var  a = 0;
    var  b = 1;    if  (b == 0){        reject ("出错了");    } else  {        resolve (a / b );    }});msg .then (function  onFulfilled  (value ) {    console .log (value )},function  onRejected (error ) {    console .err (error )})或者使⽤链式⽅式msg .then (function (value ){ console .log (value )}).catch (function (error ){  console .err (error )})----------------------------------------------------------------------------------------------------------使⽤3:把Prosime 代码放进函数中再进⾏调⽤函数返回⼀个Prosime 对象,这样就会在调⽤时才执⾏Promise 代码function  methods (){ new  Promise (function (resolve , reject ){    //当异步代码执⾏成功时,我们才会调⽤resolve(...), 当异步代码失败时就会调⽤reject(...)  $.get ('/demo',{data :'test'},res =>{  resolve ("成功!"); //代码正常执⾏!  },'json'); })}调⽤时执⾏methods ().then ();----------------------------------------------------------------------------------------------------------new  Promise (function  (resolve , reject ) {  var  a = 0;  var  b = 1;  if  (b == 0){      reject ("Diveide zero");  } else  {      resolve (a / b );  }}).then (function  (value ) {  console .log ("a / b = " + value );}).catch (function  (err ) {  console .log (err );}).finally (function  () {  console .log ("End");});
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
3.async 异步函数 执⾏结果:a / b = 0End Promise 中可使⽤catch 和finally 控制异常----------------------------------------------------------------------------------------------------------new  Promise (function  (resolve , reject ) {    console .log (1111);    resolve (2222);}).then (function  (value ) {    console .log (value );    return  3333;}).then (function  (value ) {    console .log (value );    throw  "An error";}).catch (function  (
err ) {    console .log (err );});1.resolve ()可以放置⼀个参数⽤于向下⼀个then 传值2.then 中的的函数也可以返回⼀个值传递给下⼀个then 3.如果then 接收的是⼀个Prosime 对象那么下⼀个then 相当于对这个返回的对象进⾏操作
6.then 块是默认向下顺序执⾏,return 是不能中断的,可以通过throw 来跳转⾄catch 实现中断
76
77
78
79
80
81
82
83
await和async使用方法84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
function  print (delay , message ) {    return  new  Promise (function  (resolve , reject ) {        setTimeout (function  () {            console .log (message );            resolve ();        }, delay );    });}使⽤Promise ⽅式调⽤print (1000, "First").then (function  () {    return  print (4000, "Second");}).then (functi
on  () {    print (3000, "Third");});使⽤async 异步函数调⽤async  function  asyncFunc (){ await  print (4000, "Second"); await  print (3000, "Third"); await  print (2000, "First");}asyncFunc ();1.写法和同步操作⼀样,使⽤await 指令来调⽤,await 后⾯必须跟着⼀个Promise 函数。2.异步函数会在这个Promise 运⾏中暂停,知道当前运⾏结束才继续运⾏下⾯的调⽤3.异步函数的运⾏机构和Promise ⼀样,写法上更⽅便于阅读----------------------------------------------------------------------------------------------------------⽤try -catch 块实现:async  function  asyncFunc () {    try  {        await  new  Promise (function  (resolve , reject ) {            throw  "Some error"; // 或者 reject("Some error")        });    } catch  (err ) {        console .log (err );        // 会输出 Some error    }}asyncFunc ();----------------------------------------------------------------------------------------------------------如果Promise 有⼀个正常的返回值,await 语句也会正常返回它async  function  asyncFunc () {    let  value = await  new  Promise (        function  (resolve , reject ) {            resolve ("Return value");        }    );    console .log (value );}asyncFunc ();1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。