Promise 的嵌套写法
时间: 2023-10-20 13:33:10 浏览: 35
Promise 的嵌套写法可以通过使用 `.then()` 方法来实现。下面是一个示例:
```javascript
someAsyncFunction()
.then(result1 => {
// 在这里处理第一个异步操作的结果
return anotherAsyncFunction(result1);
})
.then(result2 => {
// 在这里处理第二个异步操作的结果
return yetAnotherAsyncFunction(result2);
})
.then(result3 => {
// 在这里处理第三个异步操作的结果
console.log('最终结果:', result3);
})
.catch(error => {
// 处理错误
console.error('发生错误:', error);
});
```
在上述示例中,`someAsyncFunction`、`anotherAsyncFunction` 和 `yetAnotherAsyncFunction` 都是返回 Promise 对象的异步函数。通过使用 `.then()` 方法,我们可以在每个异步操作完成后继续执行下一个操作。
每个 `.then()` 方法返回的是一个新的 Promise 对象,因此我们可以继续链式地调用 `.then()` 方法来进行多个异步操作的嵌套。如果任何一个异步操作发生错误,会跳过后续的 `.then()` 块,直接执行 `.catch()` 块来处理错误。