直接上一个例子,拉走,打开控制台,结合代码,一目了然
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<script>
function sum(a, b) {
const promise = new Promise((resolve, reject) => {
if (typeof a != 'number' || typeof b != 'number') {
// reject参数返回一个执行错误对象,用.catch调用
reject({
msg: 'a or b not is a number'
})
}
// resolve参数返回一个执行正确对象,用.then调用
resolve({
sum: a + b
})
})
return promise
}
sum(8, 2).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
</script>
</body>
</html>