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')})
打印出:
somethingElsecase 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')})
打印出:
undefinedcase 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')
})
打印出:
somethingcase 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')
})
打印出:
somethingElsecase 4: 2513ms
执行顺序为:
doSomething()
|----------|
doSomethingElse(something)
|---------------|
finalHandler(somethingElse)
|->
解释:doSomethingElse 作为 then 参数传入不会发生值穿透,并返回一个 promise,所以会顺序执行。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。