Promise 是一个对象,代表一个可能还不可用的值——异步操作的最终结果。它有三个状态:
- pending — 初始状态,还未敲定。
- fulfilled — 成功完成(有一个值)。
- rejected — 失败(有一个原因/错误)。
一旦敲定(fulfilled 或 rejected),它是 immutable ——它不能再改变。
js
()
.( res.())
.( (user))
.( (err))
.( ());
Promise 是一个对象,代表一个可能还不可用的值——异步操作的最终结果。它有三个状态:
一旦敲定(fulfilled 或 rejected),它是 immutable ——它不能再改变。
()
.( res.())
.( (user))
.( (err))
.( ());
在 .then 内返回一个 promise 会在继续之前等待它,所以你可以避免深层嵌套的回调("callback hell"):
getUser(id)
.then(user => getPosts(user.id)) // returns a promise → chain waits for it
.then(posts => console.log(posts));
Promise.all([a, b, c]); // wait for ALL; rejects fast if any fails
Promise.allSettled([a, b]); // wait for all, get each result/error
Promise.race([a, b]); // settles with the FIRST to settle
Promise.any([a, b]); // first to FULFILL (ignores rejections)
Promise 是 async JS 的基础——它们取代了回调嵌套,通过 .catch 提供统一的错误处理,而 async/await 只是在它们之上的更好的语法。
忘记 .catch(未处理的拒绝)是一个常见的错误。