Promise
一句话解释
Promise 是 对象 representing eventual result 的 asynchronous 操作 — 成功 or 失败.
用大白话说
A promise is JavaScript's way of saying "I 做不 有答案 yet, 但 I 将 eventually." It is an object that holds the state of an async operation: pending (still waiting), fulfilled (succeeded with a value), or rejected (failed with an error).
You consume a promise with .然后() (runs on success), .catch() (runs on failure), and .最后() (runs either way). Promises can be chained: each .然后() returns a new promise, so you can sequence async steps without nesting.
Promises were introduced to solve callback hell. Instead of passing callbacks deep into functions, you call an async function, get a promise back, and chain .然后() calls linearly. 异步/等待 builds on promises to make async code look even more like synchronous code.
示例
fetch("https://api.example.com/user")
.then((response) => response.json())
.then((user) => console.log(user.name))
.catch((error) => console.error("Failed:", error));获取 返回 Promise. .然后() 链 运行 on 成功; .catch() handles 任何 错误 in 链.
工作原理
- An async operation creates a promise in the pending state.
- When the operation succeeds, the promise is fulfilled with a value.
- If it fails, the promise is rejected with a reason (error).
.然后(onFulfilled)runs when the promise fulfills..catch(onRejected)runs when the promise rejects.
常见混淆
容易混淆的对象: 回调
关键区别: 回调 是 函数 通过 到 是 called later; Promise 是 对象 representing future 值. Promise 是 chainable and 有 单个 resolution, 虽然 回调 能 是 called 多个 次数.
相关术语
相关资源
相关课程
- 异步 JavaScript
Promise, 异步, and 等待
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。