promise执行加法函数,如果成功运行这个函数,则将执行完后返回加法的结果
时间: 2023-05-31 15:05:16 浏览: 51
可以这样实现:
```javascript
function add(a, b) {
return new Promise((resolve, reject) => {
if (typeof a !== 'number' || typeof b !== 'number') {
reject('参数必须是数字');
} else {
resolve(a + b);
}
});
}
add(1, 2)
.then(result => console.log(result)) // 输出 3
.catch(error => console.error(error)); // 不会执行
add(1, '2')
.then(result => console.log(result)) // 不会执行
.catch(error => console.error(error)); // 输出 '参数必须是数字'
```
上面代码中,add函数返回一个Promise对象,如果传入的参数不是数字,就会reject返回一个错误信息;如果传入的参数是数字,就会resolve返回加法的结果。在调用add函数时,使用then方法接收resolve返回的结果,使用catch方法接收reject返回的错误信息。
相关问题
采用promise对象,实现执行一个加法的函数,如果成功运行这个函数,则将执行完后返回加法的结果
function add(a, b) {
return new Promise(function(resolve, reject) {
if (typeof a !== 'number' || typeof b !== 'number') {
reject(new Error('Inputs must be numbers'));
} else {
resolve(a + b);
}
});
}
add(1, 2)
.then(function(result) {
console.log(result); // 3
})
.catch(function(error) {
console.error(error);
});
promise执行加法函数
以下是一个使用Promise执行加法函数的示例:
```javascript
function add(a, b) {
return new Promise((resolve, reject) => {
if (typeof a !== 'number' || typeof b !== 'number') {
reject('Both arguments must be numbers');
} else {
const sum = a + b;
resolve(sum);
}
})
}
add(2, 3)
.then(result => console.log(result)) // Output: 5
.catch(error => console.error(error));
add('2', 3)
.then(result => console.log(result))
.catch(error => console.error(error)); // Output: 'Both arguments must be numbers'
```
在这个示例中,`add`函数返回了一个Promise对象。如果两个参数都是数字,则会计算它们的和并通过`resolve`方法将结果传递给`.then`回调函数。如果其中一个参数不是数字,则会通过`reject`方法将错误消息传递给`.catch`回调函数。在Promise对象被创建后,我们可以使用`.then`和`.catch`方法来处理成功和失败的情况。