什么是 Promise?
Promise 是一种异步编程解决方案,它可以让我们更方便地处理异步操作,避免回调地狱的问题。Promise 有三个状态:pending(等待中)、fulfilled(已成功)和 rejected(已失败)。一旦 Promise 的状态发生改变,就不会再改变。
如何使用 Promise?
创建 Promise
我们可以通过 Promise 构造函数来创建一个 Promise 对象:
const promise = new Promise((resolve, reject) => {
// 异步操作
// 成功时调用 resolve
// 失败时调用 reject
});Promise 构造函数接收一个函数作为参数,该函数接收两个参数:resolve 和 reject。resolve 和 reject 函数用于将 Promise 的状态从 pending 改变为 fulfilled 或 rejected。
Promise 的链式调用
Promise 可以通过链式调用来串联多个异步操作。我们可以使用 then 方法来注册 Promise 成功时的回调函数,使用 catch 方法来注册 Promise 失败时的回调函数。如果 Promise 的状态已经改变,则 then 或 catch 方法会立即执行。
promise.then((value) => {
// 成功时的回调函数
}).catch((error) => {
// 失败时的回调函数
});Promise.all 和 Promise.race
Promise.all 方法可以接收一个 Promise 数组作为参数,返回一个新的 Promise 对象。当所有 Promise 对象都成功时,Promise.all 返回的 Promise 对象会变为 fulfilled 状态,并且返回一个结果数组,数组中的结果按照 Promise 数组的顺序排列。如果其中有一个 Promise 失败,则返回的 Promise 对象会变为 rejected 状态,返回的是第一个失败的 Promise 的错误信息。
Promise.all([promise1, promise2, promise3])
.then((results) => {
// 所有 Promise 都成功时的回调函数
}).catch((error) => {
// 有一个 Promise 失败时的回调函数
});Promise.race 方法也可以接收一个 Promise 数组作为参数,返回一个新的 Promise 对象。当其中一个 Promise 对象成功或失败时,Promise.race 返回的 Promise 对象也会相应地变为 fulfilled 或 rejected 状态,并返回该 Promise 的结果或错误信息。
Promise.race([promise1, promise2, promise3])
.then((value) => {
// 第一个 Promise 成功时的回调函数
}).catch((error) => {
// 第一个 Promise 失败时的回调函数
});示例代码
下面是一个使用 Promise 的示例代码:
// www.javascriptcn.com code example
function fetchData(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
}
};
xhr.onerror = function() {
reject(new Error('Network Error'));
};
xhr.send();
});
}
fetchData('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
});在上面的示例代码中,我们使用 Promise 封装了一个异步请求数据的函数 fetchData,然后通过 then 方法注册了成功时的回调函数,通过 catch 方法注册了失败时的回调函数。当 Promise 状态发生改变时,then 或 catch 方法会立即执行。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d12b2fa941bf7134279dfd