DEV Community

codemee
codemee

Posted on

1 1

Promise.resolve 注意事項

Promise.resolve 注意事項

Promise.resolve 雖然照字面上解釋會傳回一個已經實現承諾 (fullfilled) 的 Promise 物件, 可是如果傳入的引數本來就是 Promise 物件, 就會原封不動傳回來, 請看以下的範例:

p = new Promise((r, e) => {
  e(22);
});
q = Promise.resolve(p);
console.log(p===q);
q.then(r=>console.log("r:" + r), e=>console.log("e:" + e));
Enter fullscreen mode Exit fullscreen mode

執行後會看到如下的結果:

true
e:22 
Enter fullscreen mode Exit fullscreen mode

第一個 true 表示 Promise.resolve 傳回的就是原本的 Promise 物件 p, 而且會執行 then 中的錯誤處理函式, 因此, 印出 "e:22"。如果不瞭解這一點, 就會覺得很奇怪, 已經實現承諾了, 為什麼還會執行錯誤處理函式。

這和 then/catch 的處理是不一樣的, then/catch 一定會傳回新的 Promise 物件, 並依照文件上的規則設定。

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay