// Promise用法:
因Promise是一个类,所以需要new Promise来使用
// 在new时 Promise需要传入一个参数 参数为回调函数 这个回调函数在创建时就会被立即调用
// 该回调函数有俩个参数 分别也是回调函数 resolve 和 reject(为形参名可随意起名)
// 当第一个回调参数被调用时,会调用new出来的这个对象下的then方法,then方法中的参数也是个回调函数 此时就会执行这个回调参数
// 当第二个回调参数被调用时,会调用new出来的这个对象下的catch方法,catch方法中参数也是个回调函数此时就会执行这个回调参数
const num = 1;
const promise = new Promise((resolve,reject) => {
console.log('当对象被创建时就会执行这个回调函数');
// 根据业务逻辑代码来调用回调参数
num === 1 ? resolve() : reject()
// 当执行resolve方法时 就会执行当前对象下的then方法
// 当执行reject方法时 就会执行当前对象下的catch方法
});
promise.then(res => {
console.log('当前num为1执行resolve方法,我被回调了')
});
promise.catch(res => {
console.log('当前num为其他值,执行reject方法,我被回调了')
});
// 当然也可以传参来实现数据传递
// 在调用Promise俩个回调函数时
resolve('实参');
reject('实参');
// 在对应的回调then catch中 就可以使用传递的实参
then( res => { // res 为形参 resolve调用时传递来的
console.log(res);
});
catch( err => { // err 为形参 reject调用时传递来的
console.log(err);
});