Promise 是 JavaScript 中用于处理异步操作的一种对象。它代表了一个异步操作的最终完成(或失败)及其结果值。Promise 提供了一种更清晰、更结构化的方式来处理异步代码,避免了传统的回调地狱(callback hell)问题。
基础
基本概念
-
状态(State):
pending: 初始状态,既不是成功也不是失败。
fulfilled: 操作成功完成。
rejected: 操作失败。
-
结果(Result):
- 当
Promise 的状态变为 fulfilled 时,会有一个结果值。
- 当
Promise 的状态变为 rejected 时,会有一个错误原因。
创建一个 Promise
你可以使用 Promise 构造函数来创建一个新的 Promise 对象。构造函数接受一个执行函数(executor function),该函数有两个参数:resolve 和 reject。
1
2
3
4
5
6
7
8
9
10
11
|
const myPromise = new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
const success = true; // 模拟成功或失败
if (success) {
resolve('Operation succeeded');
} else {
reject('Operation failed');
}
}, 1000);
});
|
使用 Promise
你可以通过 then() 方法来处理 Promise 的成功状态,通过 catch() 方法来处理 Promise 的失败状态。
1
2
3
4
5
6
7
|
myPromise
.then(result => {
console.log(result); // 输出: Operation succeeded
})
.catch(error => {
console.error(error); // 输出: Operation failed
});
|
1、 Promise 链式调用
then() 方法返回一个新的 Promise,因此你可以链式调用多个 then() 方法。
1
2
3
4
5
6
7
8
9
10
11
|
myPromise
.then(result => {
console.log(result); // 输出: Operation succeeded
return 'Next step';
})
.then(nextResult => {
console.log(nextResult); // 输出: Next step
})
.catch(error => {
console.error(error); // 输出: Operation failed
});
|
2、 Promise.all()
Promise.all() 方法接受一个包含多个 Promise 的数组,并返回一个新的 Promise。这个新的 Promise 在所有输入的 Promise 都成功完成时才会完成,返回一个包含所有结果的数组。如果任何一个 Promise 失败,则返回的 Promise 会立即失败。
1
2
3
4
5
6
7
8
9
10
11
|
const promise1 = Promise.resolve(1);
const promise2 = Promise.resolve(2);
const promise3 = Promise.resolve(3);
Promise.all([promise1, promise2, promise3])
.then(results => {
console.log(results); // 输出: [1, 2, 3]
})
.catch(error => {
console.error(error);
});
|
3、 Promise.race()
Promise.race() 方法接受一个包含多个 Promise 的数组,并返回一个新的 Promise。这个新的 Promise 在任何一个输入的 Promise 成功或失败时立即完成,返回第一个完成的 Promise 的结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'one');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 50, 'two');
});
Promise.race([promise1, promise2])
.then(result => {
console.log(result); // 输出: two
})
.catch(error => {
console.error(error);
});
|
4、 Promise.resolve() 和 Promise.reject() 🌟
Promise.resolve() 和 Promise.reject() 是两个静态方法,用于快速创建已经成功或失败的 Promise。
1
2
3
4
5
6
7
8
9
|
const resolvedPromise = Promise.resolve('Resolved');
resolvedPromise.then(result => {
console.log(result); // 输出: Resolved
});
const rejectedPromise = Promise.reject('Rejected');
rejectedPromise.catch(error => {
console.error(error); // 输出: Rejected
});
|
错误处理
你可以使用 catch() 方法来捕获 Promise 链中的任何错误。
1
2
3
4
5
6
7
8
9
10
11
|
myPromise
.then(result => {
console.log(result);
throw new Error('Something went wrong');
})
.then(nextResult => {
console.log(nextResult);
})
.catch(error => {
console.error(error.message); // 输出: Something went wrong
});
|
总结
Promise 是 JavaScript 中处理异步操作的重要工具,它提供了一种更清晰、更结构化的方式来处理异步代码。通过 then()、catch()、Promise.all() 和 Promise.race() 等方法,你可以轻松地处理复杂的异步操作,避免回调地狱,并提高代码的可读性和可维护性。