promise嵌套调用
时间: 2023-07-06 21:43:32 浏览: 160
嵌套的 Promise 调用也称为 Promise 链。在 Promise 链中,每个 Promise 的结果都会传递给下一个 Promise,从而实现一系列的异步操作。Promise 链的代码可读性较高,可以更清晰地表达异步操作之间的依赖关系。
下面是一个嵌套的 Promise 调用的示例代码:
```
function asyncOperation() {
return new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
resolve('data');
}, 1000);
});
}
asyncOperation()
.then((result) => {
return new Promise((resolve, reject) => {
// 异步操作
setTimeout(() => {
resolve(result + ' processed');
}, 1000);
});
})
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});
```
在这个例子中,`asyncOperation` 函数返回一个 Promise 对象,它模拟了一个异步操作。在 Promise 链的第一个 `then` 方法中,我们创建了另一个 Promise 对象,它也模拟了一个异步操作,将前一个 Promise 的结果作为参数传递给了它。在 Promise 链的第二个 `then` 方法中,我们打印了最终的结果。
如果 Promise 链中的某个 Promise 抛出了异常,它会被 Promise 链中的 `catch` 方法捕获。如果没有在 Promise 链中的任何一个 Promise 中捕获异常,它就会被全局的 `catch` 方法捕获。
阅读全文
相关推荐
















