怎样创建一个promise
结合项目 一般的使用场景 都是使用网络请求之后 需要同步做的事情,话不多说 上代码
FunAll.js ------> 函数集合
const getCouponList = () => {
return new Promise((resolve, reject) => {
//这里放入网络请求
Http.post('/coupon/getCouponInfo',[params],).then(source => {
//拿到source函数 resolve出来 在需要调用getCouponList 函数的地方可以直接使用 如果这个函数在多个调用函数里面有相同的业务逻辑 当然也可以在这里把业务逻辑写好 然后resolve(true) ,具体怎么使用看场景。
resolve(source);
}).catch((error) => {
//执行 catch到错误的业务逻辑 比如弹框告诉网络拥挤什么的。。。
reject(error);// resolve(false)与resolve(true) 对应
})
})
}
const getCouponListAfterFun = () => {
return new Promise((resolve, reject) => {
Http.post('/coupon/getCouponListAfter ',[params],).then(source => {
resolve(source);
}).catch((error) => {
reject(error);
})
})
}
export {
getCouponList ,
getCouponListAfterFun
}
coupon.js----->调用函数的页面
先导入 FunAll.js
- 一个promise
getCouponList().then((res) => {
if (res) {
//拿到数据之后 进行业务逻辑操作
}
})
- 多个promise
假设 getCouponListAfterFun 在getCouponList之后执行
getCouponList().then((res) => {
if (res) {
//拿到数据之后 进行业务逻辑操作
return getCouponListAfterFun ();//return出改数据
}
}).then((res) => {
if (res) {
//拿到数据之后 进行业务逻辑操作
}
})------------------------------》如果还有需要同步的函数 继续then