標籤:

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

目錄:

  1. 深入 Promise(一)——Promise 實現詳解

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

  3. 深入 Promise(三)——命名 Promise

twitter 上有一道關於 Promise 的題,執行順序是怎樣?見下圖:

我們假設 doSomething 耗時 1s,doSomethingElse 耗時 1.5s:

function doSomething() {n return new Promise((resolve, reject) => {n setTimeout(() => {n resolve(something)n }, 1000)n })n}nnfunction doSomethingElse() {n return new Promise((resolve, reject) => {n setTimeout(() => {n resolve(somethingElse)n }, 1500)n })n}n

1. 第一種情況:

console.time(case 1)ndoSomething().then(() => {n return doSomethingElse()n}).then(function finalHandler(res) {n console.log(res)n console.timeEnd(case 1)n})n

列印出:

somethingElsencase 1: 2509msn

執行順序為:

doSomething()n|----------|n doSomethingElse()n |---------------|n finalHandler(somethingElse)n |->n

解釋:正常的 Promise 用法。

2. 第二種情況:

console.time(case 2)ndoSomething().then(function () {n doSomethingElse()n}).then(function finalHandler(res) {n console.log(res)n console.timeEnd(case 2)n})n

列印出:

undefinedncase 2: 1009msn

執行順序為:

doSomething()n|----------|n doSomethingElse()n |---------------|n finalHandler(undefined)n |->n

解釋:因為沒有使用 return,doSomethingElse 在 doSomething 執行完後非同步執行的。

3. 第三種情況:

console.time(case 3)ndoSomething().then(doSomethingElse())n .then(function finalHandler(res) {n console.log(res)n console.timeEnd(case 3)n })n

列印出:

somethingncase 3: 1008msn

執行順序為:

doSomething()n|----------|ndoSomethingElse()n|---------------|n finalHandler(something)n |->n

解釋:上面代碼相當於:

console.time(case 3)nvar doSomethingPromise = doSomething()nvar doSomethingElsePromise = doSomethingElse()ndoSomethingPromise.then(doSomethingElsePromise)n .then(function finalHandler(res) {n console.log(res)n console.timeEnd(case 3)n })n

而我們知道 then 需要接受一個函數,否則會值穿透,所以列印 something。

4. 第四種情況:

console.time(case 4)ndoSomething().then(doSomethingElse)n .then(function finalHandler(res) {n console.log(res)n console.timeEnd(case 4)n })n

列印出:

somethingElsencase 4: 2513msn

執行順序為:

doSomething()n|----------|n doSomethingElse(something)n |---------------|n finalHandler(somethingElse)n |->n

解釋:doSomethingElse 作為 then 參數傳入不會發生值穿透,並返回一個 promise,所以會順序執行。


推薦閱讀:

採用Symbol和process.nextTick實現Promise
《球球大作戰》源碼解析——(1)運行起來
nodeJS 2016年官方技術調查報告
node-webkit教程(11)Platform Service之shell
D2 - 打造高可靠與高性能的React同構解決方案

TAG:Promise | Nodejs |