1、顺序执行带来的问题
下面代码模拟了三个请求接口,也就是三个请求没有任何依赖关系,却要等到上一个执行完才执行下一个,带来时间上的浪费。
(async () => {const getList1 = await getList1();const getList2 = await getList1();const getList3 = await getList2();})();
解决方案:
(async () => {const listPromise = getList();const anotherListPromise = getAnotherList();await listPromise;await anotherListPromise;})();// 也可以使用(async () => {Promise.all([getList(), getAnotherList()]).then(...);})();
2、try catch 捕获错误
使用 try catch 捕获错误,当我们需要捕获多个错误并做不同的处理时,try catch 会导致代码杂乱:
async function asyncTask(cb) {try {const res1 = await request1(resByRequest1); //resByRequest1返回值为promiseif(!res1) return cb('error1');} catch(e) {return cb('error2');}try {const res2 = await request2(resByRequest2); //resByRequest2返回值为promise} catch(e) {return cb('error3');}}
简化错误捕获:添加一个中间函数:
export default function to(promise) {return promise.then(data => {return [null, data];}).catch(err => [err]);}
错误捕获的代码:
async function asyncTask() {let err, data[err, data1] = await to(resByRequest1);if(!data1) throw new Error('xxxx');[err, data2] = await to(resByRequest2);if(!data2) throw new Error('xxxx');}
3、练习题目
红灯三秒亮一次,绿灯一秒亮一次,黄灯2秒亮一次;如何让三个灯不断交替重复亮灯?(用 Promse 实现)
function red(){console.log('red');}function green(){console.log('green');}function yellow(){console.log('yellow');}var light = function(timmer, cb){return new Promise(function(resolve, reject) {setTimeout(function() {cb();resolve();}, timmer);});};var step = function() {Promise.resolve().then(function(){return light(3000, red);}).then(function(){return light(2000, green);}).then(function(){return light(1000, yellow);}).then(function(){step();});}step();
