首先,使用定时器模拟实现异步的嵌套数据请求:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>异步操作</title> 8 </head> 9 <body> 10 <script> 11 var time = 0; 12 setTimeout(()=>{ 13 time ++; 14 console.log(time); 15 setTimeout(()=>{ 16 time ++; 17 console.log(time); 18 setTimeout(()=>{ 19 time ++; 20 console.log(time); 21 },1000) 22 },1000) 23 },1000) 24 </script> 25 26 </body> 27 </html>
结果:
改造为用Promise处理:
1 <script> 2 var time = 0; 3 new Promise((res,rej)=>{ 4 5 setTimeout(()=>{ 6 time++; 7 res(time); //成功时调用 8 },1000) 9 10 }).then((time)=>{ 11 console.log(time); 12 return new Promise((res,rej) => { //return 实现参数返回 13 setTimeout(()=>{ 14 time++; 15 res(time); 16 },1000) 17 }) 18 19 }).then((time)=> { 20 console.log(time); 21 return new Promise((res,rej) => { 22 setTimeout(()=>{ 23 time++; 24 res(time); 25 },1000) 26 }) 27 28 }).then((time)=> { 29 30 console.log(time); 31 return new Promise((res,rej) => { 32 setTimeout(()=>{ 33 res(); 34 },1000) 35 }) 36 37 }) 38 </script>
结果: