搜索文档
Promise 的优势
- 支持链式调用,避免回调地狱
- 指定回调函数的方式更灵活
基本语法
js
// 生成指定区间的随机整数
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 定义 Promise
const fun = new Promise((resolve, reject) => {
setTimeout(() => {
let num = getRandomInt(1, 100);
if (num > 40) resolve(num);
else reject(num);
}, 1000)
})
// 调用 Promise
fun.then(e => {
console.log('成功:', e);
}, e => {
console.log('失败', e);
})