Promise 是 JavaScript 中用于处理异步操作的一种对象,它代表了一个异步操作的最终完成(或失败)及其结果值。Promise 有三种状态:
1. pending(进行中):初始状态,既不是成功也不是失败。
2. fulfilled(已成功):操作成功完成。
3. rejected(已失败):操作失败。
基本使用
Promise 通常用于处理异步操作,比如网络请求、文件读取等。以下是 Promise 的基本使用方法:
1. 创建一个 Promise
const myPromise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
const success = true; // 假设异步操作成功
if (success) {
resolve("操作成功!"); // 成功时调用 resolve
} else {
reject("操作失败!"); // 失败时调用 reject
}
}, 1000);
});
2. 使用 then 和 catch 处理 Promise
myPromise
.then((result) => {
console.log(result); // 输出:操作成功!
})
.catch((error) => {
console.error(error); // 如果 reject,这里会捕获错误
});
链式调用
Promise 支持链式调用,可以将多个异步操作按顺序执行:
Promise.resolve("第一步")
.then((result) => {
console.log(result); // 输出:第一步
return "第二步"; // 返回值会被下一个 then 接收
})
.then((result) => {
console.log(result); // 输出:第二步
return "第三步";
})
.then((result) => {
console.log(result); // 输出:第三步
})
.catch((error) => {
console.error(error);
});
Promise.all
Promise.all 用于并行执行多个 Promise,并等待所有 Promise 完成:
const promise1 = Promise.resolve("第一个 Promise");
const promise2 = new Promise((resolve) => setTimeout(() => resolve("第二个 Promise"), 1000));
const promise3 = Promise.reject("第三个 Promise");
Promise.all([promise1, promise2, promise3])
.then((results) => {
console.log(results); // 如果所有 Promise 都成功,输出:["第一个 Promise", "第二个 Promise", "第三个 Promise"]
})
.catch((error) => {
console.error(error); // 如果任何一个 Promise 失败,这里会捕获错误
});
Promise.race
Promise.race 用于并行执行多个 Promise,但只要其中一个 Promise 完成(无论成功还是失败),就会立即返回结果:
const promise1 = new Promise((resolve) => setTimeout(() => resolve("第一个 Promise"), 1000));
const promise2 = new Promise((resolve) => setTimeout(() => resolve("第二个 Promise"), 500));
Promise.race([promise1, promise2])
.then((result) => {
console.log(result); // 输出:第二个 Promise(因为它的执行时间更短)
})
.catch((error) => {
console.error(error);
});
错误处理
Promise 的错误处理通常使用 .catch() 方法:
const myPromise = new Promise((resolve, reject) => {
reject("出错了!");
});
myPromise
.then((result) => console.log(result))
.catch((error) => console.error(error)); // 输出:出错了!
实际应用场景
1. 网络请求:
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
2. 文件读取:
const fs = require("fs").promises;
fs.readFile("file.txt", "utf8")
.then((data) => console.log(data))
.catch((error) => console.error(error));
总结
Promise 是处理异步操作的重要工具,它提供了比回调函数更清晰的代码结构。通过 then、catch、Promise.all 和 Promise.race 等方法,可以灵活地处理异步任务。现代 JavaScript 中,async/await 语法也是基于 Promise 的,进一步简化了异步代码的书写。