在Promise的.then和catch中怎么调用其它函数
时间: 2023-12-14 08:37:45 浏览: 76
在Promise的.then和catch中,可以通过调用其它函数来处理Promise返回的结果或错误信息。例如:
```
// 定义一个函数
function handleResult(result) {
console.log("处理结果:", result);
}
// 定义另一个函数
function handleError(error) {
console.error("处理错误:", error);
}
// 创建一个Promise对象
const promise = new Promise((resolve, reject) => {
// 模拟异步操作
setTimeout(() => {
const num = Math.random();
if (num > 0.5) {
resolve(num);
} else {
reject(new Error("数字小于0.5"));
}
}, 1000);
});
// 在Promise的then中调用handleResult函数
promise.then(handleResult);
// 在Promise的catch中调用handleError函数
promise.catch(handleError);
```
在上述代码中,我们定义了两个函数`handleResult`和`handleError`来处理Promise返回的结果或错误信息。在Promise的then和catch方法中,我们分别调用这两个函数来处理Promise的结果和错误信息。当Promise的状态变为resolved时,它会调用handleResult函数;当Promise的状态变为rejected时,它会调用handleError函数。
阅读全文
相关推荐


















