目录:
twitter 上有一道关于 Promise 的题,执行顺序是怎样?见下图:
我们假设 doSomething 耗时 1s,doSomethingElse 耗时 1.5s:
function doSomething() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('something')
}, 1000)
})
}
function doSomethingElse() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('somethingElse')
}, 1500)
})
}
1. 第一种情况:
console.time('case 1')
doSomething().then(() => {
return doSomethingElse()
}).then(function finalHandler(res) {
console.log(res)
console.timeEnd('case 1')
})
打印出:
somethingElse
case 1: 2509ms
执行顺序为:
doSomething()
|----------|
doSomethingElse()
|---------------|
finalHandler(somethingElse)
|->
解释:正常的 Promise 用法。
2. 第二种情况:
console.time('case 2')
doSomething().then(function () {
doSomethingElse()
}).then(function finalHandler(res) {
console.log(res)
console.timeEnd('case 2')
})
打印出:
undefined
case 2: 1009ms
执行顺序为:
doSomething()
|----------|
doSomethingElse()
|---------------|
finalHandler(undefined)
|->
解释:因为没有使用 return,doSomethingElse 在 doSomething 执行完后异步执行的。
3. 第三种情况:
console.time('case 3')
doSomething().then(doSomethingElse())
.then(function finalHandler(res) {
console.log(res)
console.timeEnd('case 3')
})
打印出:
something
case 3: 1008ms
执行顺序为:
doSomething()
|----------|
doSomethingElse()
|---------------|
finalHandler(something)
|->
解释:上面代码相当于:
console.time('case 3')
var doSomethingPromise = doSomething()
var doSomethingElsePromise = doSomethingElse()
doSomethingPromise.then(doSomethingElsePromise)
.then(function finalHandler(res) {
console.log(res)
console.timeEnd('case 3')
})
而我们知道 then 需要接受一个函数,否则会值穿透,所以打印 something。
4. 第四种情况:
console.time('case 4')
doSomething().then(doSomethingElse)
.then(function finalHandler(res) {
console.log(res)
console.timeEnd('case 4')
})
打印出:
somethingElse
case 4: 2513ms
执行顺序为:
doSomething()
|----------|
doSomethingElse(something)
|---------------|
finalHandler(somethingElse)
|->
解释:doSomethingElse 作为 then 参数传入不会发生值穿透,并返回一个 promise,所以会顺序执行。
编程书籍推荐
看完两件小事
如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:
- 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
- 关注公众号 「画漫画的程序员」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程
本文著作权归作者所有,如若转载,请注明出处
转载请注明:文章转载自「 Js中文网 · 前端进阶资源教程 」https://www.javascriptc.com