分享2个实用的JS小技巧

tech2025-10-26  4

转载自品略图书馆 http://www.pinlue.com/article/2020/08/2310/3411146362735.html

 

如何优雅的捕获错误

之前的经常会出现这样的代码逻辑:

                       // 假设这是一个API接口调用function userInfo () { return new Promise((resolve, reject) => { setTimeout(() => { resolve({ data: { name: "张三", age: 18 }, code: "000" }) }, 3000) })}// 在页面加载调用这个函数async function getUserInfo () { try { let res = await userInfo() console.log("正常处理...") } catch (error) { // 错误捕获 }}

 

每次都要写 try/catch 语句,这样是非常麻烦的,其实我们可以再进一步封装。

         async function useCatch (asyncFunc) { try { const res = await asyncFunc() return [null, res] } catch (error) { return [error, null] }}

 

然后在任何你需要的文件中引入上面这个帮助函数,这个帮助函数的封装规则是遵循错误优先的规则,这点和 node 比较类似,然后函数的命名是遵循 hooks 的形式。

       async function getUserInfo () { let [err, res] = await useCatch(userInfo) if (!err) { console.log("正常处理...") }}

 

是不是很棒!!!

async/await的特殊用法

任何具有 .then 方法的对象都可以与 async/await 一起使用。一起来看下面代码的例子,写了 sleep 函数:

               class Sleep { constructor(timeout) { this.timeout = timeout; } then(resolve, reject) { const startTime = Date.now(); setTimeout(() => resolve(Date.now() - startTime), this.timeout); }}(async () => { const actualTime = await new Sleep(1000); console.log(actualTime);})();

 

根据这个套路,我还写了个接口轮询的例子:

                                             const ServerMock = { count: 0, getData() { if (this.count === 2) { return Promise.resolve([{ name: "SomeName" }]); } else { this.count++; return Promise.reject("Error"); } }};function fetchData(limit, time) { return { then(resolve, reject) { const retry = setInterval(async () => { limit--; try { console.log("Trying...."); const data = await ServerMock.getData(); if (data) { console.log("Resolve"); clearInterval(retry); resolve(data); } } catch { if (limit === 0) { clearInterval(retry); reject("Limit Reached"); } } }, time); } };}(async () => { try { const result = await fetchData(3, 1000); console.log(result); } catch (err) { console.log(err); }})();

 

轮询常见的就是间隔一段时间进行重复调用,还有一种就是没有间隔时间,这种我们称为快轮询。

                     const ServerMock = { count: 0, getData() { if (this.count === 2) { return Promise.resolve([{ name: "SomeName" }]); } else { this.count++; return Promise.reject("Error"); } }};const retry = (attempts, action) => { const promise = action() return attempts > 0 ? promise.catch(() => retry(attempts - 1, action)) : promise}(async () => { let res = await retry(5, () => ServerMock.getData()) console.log(res)})

 

这是高阶函数的写法,代码中通过参数传入一个回调函数,通过判断接口请求是成功还是失败,如果是失败就会被 catch 进行捕获,然后进入下一轮的接口调用。

最新回复(0)