当前位置: 首页 > 后端技术 > Node.js

深入Promise(二)——Promise攻击

时间:2023-04-03 22:32:15 Node.js

twitter上有一个关于Promise的问题,执行顺序是怎样的?见下图:我们假设doSomething耗时1s,doSomethingElse耗时1.5s:1000)})}functiondoSomethingElse(){returnnewPromise((resolve,reject)=>{setTimeout(()=>{resolve('somethingElse')},1500)})}第一种情况:console.time('case1')doSomething().then(()=>{returndoSomethingElse()}).then(functionfinalHandler(res){console.log(res)console.timeEnd('case1')})打印出来:somethingElsecase1:2509ms执行顺序为:doSomething()|----------|doSomethingElse()|----------------|finalHandler(somethingElse)|->解释:正常的Promise用法。第二种情况:console.time('case2')doSomething().then(function(){doSomethingElse()}).then(functionfinalHandler(res){console.log(res)console.timeEnd('case2')})打印出:undefinedcase2:1009ms执行顺序为:doSomething()|------------|doSomethingElse()|----------------|finalHandler(undefined)|->解释:因为没有使用return,doSomethingElse是在doSomething执行完之后异步执行的。第三种情况:console.time('case3')doSomething().then(doSomethingElse()).then(functionfinalHandler(res){console.log(res)console.timeEnd('case3')})打印out:somethingcase3:1008ms执行顺序是:doSomething()|------------|doSomethingElse()|--------------|finalHandler(something)|->解释:上面的代码等同于:console.time('case3')vardoSomethingPromise=doSomething()vardoSomethingElsePromise=doSomethingElse()doSomethingPromise.then(doSomethingElsePromise).then(functionfinalHandler(res){console.log(res)console.timeEnd('case3')})我们知道then需要接受一个函数,否则值会通过,所以打印一些东西。第四种情况:console.time('case4')doSomething().then(doSomethingElse).then(functionfinalHandler(res){console.log(res)console.timeEnd('case4')})打印出来:somethingElsecase4:2513ms执行顺序为:doSomething()|----------|doSomethingElse(something)|----------------|finalHandler(somethingElse)|->说明:doSomethingElse作为then参数传入,没有值穿透,返回的是promise,所以会顺序执行。