一.为啥要用Promise?
当方法回调很多很繁琐时,代码嵌套太深,可读性很差,可用Promise
二.概念及用法
Promise 承诺
//异步 let isForget = false let getPs = new Promise((resolve, reject) => { if (isForget) { let ps = { color: "red", price: "$99" } resolve(ps) } else { let err = new Error("报错了") reject(err) } }) //基本用法 let testFn = function() { getPs.then((success) => { console.log(success) }).catch((failure) => { console.log(failure) }) } testFn()
链式调用
//异步 let isForget = true let getPs = new Promise((resolve, reject) => { if (isForget) { let lv = { color: "red", price: "$99" } resolve(lv) } else { let err = new Error("wo报错了!!!!") reject(err) } }) //链式调用 let getBuyall = (lv) => { let cloth = { size: "M", color: "green" } let msg = { massage: "我的口红yanse:" + lv.color + "我的衣服大小尺寸:" + cloth.size, lv: lv, cloth: cloth } return Promise.resolve(msg) } let testFn = () => { getPs .then(getBuyall) .then((success) => { console.log(success) }).catch((failure) => { console.log(failure.message) }) } testFn()