深入 Promise(二)——進擊的 Promise


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,所以會順序執行。

轉自:https://zhuanlan.zhihu.com/p/25198178


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM