在使用 async…await 方法时,经常采用 try…catch 捕获异常,如果有多个异步操作,需要每一次书写 try…catch。这样代码的简洁性较差,为了使代码更加的优雅,我们通过使用 await-to-js
js 库来处理异常。
常规写法
代码简洁性较差
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| let flag = true;
function fetchVehicle() { return new Promise((resolve, reject) => { setTimeout(() => { if (flag) { resolve(true); } else { reject(false); } }, 1000); }); }
function fetchOrganization() { return new Promise((resolve, reject) => { setTimeout(() => { if (flag) { resolve(true); } else { reject(false); } }, 2000); }); }
async function fn() { try { let res = await fetchVehicle(); console.log(res); } catch (error) { console.log(error); }
try { let res = await fetchOrganization(); console.log(res); } catch (error) { console.log(error); } }
fn();
|
await-to-js 优雅写法
核心思路
抽离一个公共方法,将 try…catch 抽离
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| let flag = true;
function fetchVehicle() { return new Promise((resolve, reject) => { setTimeout(() => { if (flag) { resolve(true); } else { reject(false); } }, 1000); }); }
async function fn() { let [error, res] = await fetchVehicle() .then(res => [null, res]) .catch(error => [error]);
console.log("error", error); console.log("res", res); }
fn();
|
封装方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const to = promise => { return promise.then(res => [null, res]).catch(error => [error]); };
let flag = true;
function fetchVehicle() { return new Promise((resolve, reject) => { setTimeout(() => { if (flag) { resolve(true); } else { reject(false); } }, 1000); }); }
async function fn() { let [error, res] = await to(fetchVehicle()) console.log("error", error); console.log("res", res); }
fn();
|
await-to-js 源码参考