3.1 创建 Promise 链
Promise 链允许你按顺序执行多个异步操作,把一个操作的结果传递到下一个。这让你的代码更容易读和管理。而且,Promise 提供强大的错误处理功能,这使得你可以创建可靠、抗崩溃的应用。
主要概念
Promise 链是通过从 then 方法返回一个新的 Promise 来创建的。每个 then 方法返回一个新 Promise,这样就可以构建顺序异步操作。
简单的 Promise 链示例
在这个例子中,每个 then 方法执行它自己的操作并将结果传递给下一个 then 方法。
JavaScript
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Step 1 completed');
}, 1000);
});
promise
.then((result) => {
console.log(result); // 输出: Step 1 completed
return 'Step 2 completed';
})
.then((result) => {
console.log(result); // 输出: Step 2 completed
return 'Step 3 completed';
})
.then((result) => {
console.log(result); // 输出: Step 3 completed
})
.catch((error) => {
console.error(error);
});
异步操作的 Promise 链示例
在这个例子中,每个 then 方法在执行下一个步骤前都要等待异步操作完成:
JavaScript
function asyncOperation(step) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`${step} completed`);
}, 1000);
});
}
asyncOperation('Step 1')
.then((result) => {
console.log(result); // 输出: Step 1 completed
return asyncOperation('Step 2');
})
.then((result) => {
console.log(result); // 输出: Step 2 completed
return asyncOperation('Step 3');
})
.then((result) => {
console.log(result); // 输出: Step 3 completed
})
.catch((error) => {
console.error(error);
});
3.2 Promise 链中的错误处理
catch 方法用于处理 Promise 链中的错误。如果任何一个 Promise 出错,错误会传递到最近的 catch 方法。这使得你能集中处理错误,提升代码的可读性和维护性。
错误处理示例
在这个例子中,Step 2 中发生的错误会被 catch 方法捕获,后续的 then 方法不再执行:
JavaScript
function asyncOperation(step, shouldFail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject(`${step} failed`);
} else {
resolve(`${step} completed`);
}
}, 1000);
});
}
asyncOperation('Step 1')
.then((result) => {
console.log(result);
return asyncOperation('Step 2', true); // 这个操作会失败
})
.then((result) => {
console.log(result); // 这段代码不会执行
return asyncOperation('Step 3');
})
.then((result) => {
console.log(result); // 这段代码不会执行
})
.catch((error) => {
console.error('Error:', error); // 输出: Error: Step 2 failed
});
特定步骤中的错误处理
有时候需要在特定步骤中处理错误而不终止整个链的执行。这可以通过嵌套的 then 和 catch 方法实现。
特定步骤中的错误处理示例
在这个例子中,Step 2 的错误被本地处理,链继续执行并恢复的值:
JavaScript
function asyncOperation(step, shouldFail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject(`${step} failed`);
} else {
resolve(`${step} completed`);
}
}, 1000);
});
}
asyncOperation('Step 1')
.then((result) => {
console.log(result);
return asyncOperation('Step 2', true).catch((error) => {
console.warn('Handled error in Step 2:', error);
return 'Recovered from Step 2 error';
});
})
.then((result) => {
console.log(result); // 输出: Recovered from Step 2 error
return asyncOperation('Step 3');
})
.then((result) => {
console.log(result); // 输出: Step 3 completed
})
.catch((error) => {
console.error('Error:', error); // 这段代码不会执行
});
3.3 使用 finally
finally 方法用于执行无论 Promise 成功还是失败都要运行的代码。它对于执行最后的动作,比如资源清理,特别有用。
finally 使用示例:
JavaScript
function asyncOperation(step, shouldFail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldFail) {
reject(`${step} failed`);
} else {
resolve(`${step} completed`);
}
}, 1000);
});
}
asyncOperation('Step 1')
.then((result) => {
console.log(result);
return asyncOperation('Step 2');
})
.then((result) => {
console.log(result);
return asyncOperation('Step 3');
})
.catch((error) => {
console.error('Error:', error);
})
.finally(() => {
console.log('All operations completed'); // 无论如何都会执行
});
在这个例子中,无论是否发生错误,finally 方法都会执行。
GO TO FULL VERSION