/**
* 传入参数 n,表示这个函数执行的时间(毫秒)
* 执行的结果是 n + 200,这个值将用于下一步骤
*/functiontakeLongTime(n){returnnewPromise(resolve=>{setTimeout(()=>resolve(n +200), n);});}functionstep1(n){
console.log(`step1 with ${n}`);returntakeLongTime(n);}functionstep2(n){
console.log(`step2 with ${n}`);returntakeLongTime(n);}functionstep3(n){
console.log(`step3 with ${n}`);returntakeLongTime(n);}
8.1、用 Promise 方式来实现这三个步骤的处理
functiondoIt(){
console.time("doIt");const time1 =300;step1(time1).then(time2=>step2(time2)).then(time3=>step3(time3)).then(result=>{
console.log(`result is ${result}`);
console.timeEnd("doIt");});}doIt();// step1 with 300// step2 with 500// step3 with 700// result is 900// doIt: 1507.251ms//输出结果 result 是 step3() 的参数 700 + 200 = 900。doIt() 顺序执行了三个步骤。//一共用了 300 + 500 + 700 = 1500 毫秒,和 console.time()/console.timeEnd() 计算的结果一致。
8.2、用 async/await 来实现
asyncfunctiondoIt(){
console.time("doIt");const time1 =300;const time2 =awaitstep1(time1);const time3 =awaitstep2(time2);const result =awaitstep3(time3);
console.log(`result is ${result}`);
console.timeEnd("doIt");}doIt();//step1 with 300//step2 with 500//step3 with 700//result is 900// doIt: 1504.81689453125 ms