//promise抛出异常 new Promise((resolve,reject)=>{ resolve("成功") }).then(res=>{ if(res !== 200){ // throw new Error("错误") // 或者 return Promise.reject("异常") } }).catch(error=>{ // console.log(error.message); console.log(error); })
promise的队列,按顺序执行:原理是需要等待上一个promise执行完才可以执行下一个
//promise按顺序执行代码的封装 /* 按顺序执行的话,就是等上一个primise执行完,再执行下一个 */ //1.这个是最基础的方式,代码比较冗杂 let promise =Promise.resolve("薯片"); promise.then(res =>{ return new Promise(resolve=>{ console.log(res); setTimeout(() => { resolve(res +"好吃") }, 1000); }) }).then(res =>{ return new Promise(resolve=>{ console.log(res); setTimeout(() => { resolve(res +"不能多吃") }, 1000); }) }).then(res=>{ console.log(res); })
2.该方式简化了 这里的promise的赋值就是相当于上一个promise执行完后,resolve()了,才执行下一个
let promise = Promise.resolve("薯片"); promise = promise.then(res => { return new Promise(resolve => { console.log(res); setTimeout(() => { resolve(res + "好吃") }, 1000); }) }) promise = promise.then(res =>{ return new Promise(resolve => { console.log(res); setTimeout(() => { resolve(res +"不能多吃") }, 1000); }) }) promise.then(res =>{ return new Promise(resolve => { console.log(res); }) })
3.最佳方式 function query(nums) { let promise = Promise.resolve(); nums.forEach(item => { promise = promise.then(() => { return new Promise(resolve => { setTimeout(() => { console.log(item); resolve() }, 1000); }) }) }); } query([1, 2, 3, 4, 5, 6])
//结果都是一秒一秒按顺序执行
function query(nums) { let promise = Promise.resolve(); nums.forEach(item => { promise = promise.then(() => { return item(); }) }); } function p1() { return new Promise(resolve => { setTimeout(() => { console.log("p1"); resolve() }, 1000); }) } function p2() { return new Promise(resolve => { setTimeout(() => { console.log("p2"); resolve() }, 1000); }) } query([p1, p2])