ES7的 async/await 组合相信如今你们已经用得炉火纯青了,是一个异步请求目前较优的处理的方案。为了保证程序的稳定运行,咱们还会加上 try/catch 处理可能抛出的错误。
文章篇幅不长,可慢慢品 ~前端
// 模拟异步请求 const sleep = (isSuccess) => { return new Promise((resolve, reject) => { setTimeout(() => { if (isSuccess) { resolve("success"); } else { reject("failure"); } }, 1000); }); }; const getRes1 = async () => { const res1 = await sleep(false); // Promise 返回 reject ,底下的代码块不被执行 console.log("do something..."); }; getRes1();
调用 getRes1()
会发生什么ios
一个未捕获的错误axios
浏览器的报错,咱们是确定要处理的,由于这可能会影响到程序的正常运行。后端
const res1 = await sleep(false);
底下的代码不被执行咱们能够通俗的理解,await xxx()
底下的代码块都是 Promise 返回的 resolve,若是 Promise 返回的是 reject,那么代码块将不会被执行。浏览器
可是若是是这种场景是能够执行的,由于它们已经不在一个相同的“代码路径”,如:框架
const created = () => { getRes1(); console.log("do something..."); }; created(); // do something...
虽然不影响程序的运行,可是程序依然会报错。若是咱们有在前端工程里有加入错误监控,如 Fundebug ,或者其余。那么将会有不少 error 级的日志,可能会混淆咱们去排查/更准确的跟踪错误。异步
咱们在实际的业务中,通常会用第三方请求框架如 Axios
,咱们还会与友好的后端小伙伴约定接口返回体,如:async
interface IResult<T> { code: 200 | 500; data: T | null; message: string; }
接下来咱们来模拟一下常见的业务场景,如:获取用户信息post
Axios.js【模拟】this
const Axios = (function () { function Axios(isTimeout = false, isExist = true) { this.isTimeout = isTimeout; this.isExist = isExist; } Axios.prototype.get = function (path, params = {}) { const resObj = ({ code, data = null, message }) => ({ code, data, message }); return new Promise((resolve, reject) => { setTimeout(() => { // 当接口请求没有错误 if (!this.isTimeout) { // 当用户存在 if (this.isExist) { resolve( resObj({ code: 200, data: { id: 1, name: "张三" }, message: "获取用户成功" }) ); } else { // 当用户不存在 resolve( resObj({ code: 500, message: "用户不存在" }) ); } } // 当接口请求出现错误,如请求超时 else { reject("timeout of 10000ms exceeded"); } }, 1000); }); }; Axios.prototype.post = function (path, params) {}; return Axios; })(); export default Axios;
调用
const axios = new Axios(true); const created = async () => { try { const { code, data, message } = await axios.get("/getUserInfo"); if (code === 200) { // do something... console.log(data); } else if (code === 500) { // do something... alert(message); } } catch (err) { console.log("err :>> ", err); } }; created(); // err :>> timeout of 10000ms exceeded
这里,咱们老老实实的用了 try/catch 进行包裹,防止控制台报超时错误。
回顾刚刚咱们有说到的,
若是在 await 底下的代码,不在一个相同的“代码路径”,那么是不会影响到程序继续运行的,只是会报了个错,可是会影响到咱们定位程序中的一些错误问题,这就会让咱们有一种 “不加 try/catch 不行,加了又以为多余的感受” ,若是在一些复杂的业务场景下,冥冥之中就会提高咱们的心智负担。
让咱们再看下标题:async/await 必定要加 try/catch 吗?答:能够不要加。
keep going >>>
二次封装 "Axios",
对于 Axios ,小伙伴们应该都是 “老封装了” ,那这里咱们再来探讨下
MyAxios.js
import Axios from "./Axios"; const axios = new Axios(true); const MyAxios = (function () { function MyAxios() {} MyAxios.prototype.get = function (path, params = {}) { return axios.get(path).catch((err) => { // return Promise.resolve({ // code: 444, // data: null, // message: "catch error", // err // }); // 可不用 Promise.resolve 静态方法,由于在Promise链里返回的都会是一个 Promise 对象 return { code: 444, data: null, message: "catch error", err }; }); }; MyAxios.prototype.post = function (path, params) { return axios.post(path).catch((err) => { return { code: 444, data: null, message: "catch error", err }; }); }; return MyAxios; })(); export default MyAxios;
调用
const myAxios = new MyAxios(); const created = async () => { const { code, data, message, err } = await myAxios.get("/getUserInfo"); if (code === 200) { // do something... console.log(data); } else if (code === 500) { // do something... alert(message); } // 不用到则不写 else if (code === 444) { console.log(message); console.log("err :>> ", err); } }; created();
咱们经过二次封装,把 Axios 返回的 reject ,捕获(catch)以后 return 一个咱们前端本身约定的 code 是444的,多了一个 err 字段的对象。这样子咱们就不须要在每一个有 async/await 的地方都用 try/catch 进行包裹来防止系统报错,若是这个接口须要你在 “catch 时” 处理一些业务逻辑,那就判断 code === 444,不须要的话,就不用写。但一般,咱们会在 MyAxios.js 用一种全局弹框的方式,来友好的告知用户:“接口有点问题,请稍后再试”。