2个实用的JS小技巧

如何优雅的捕获错误

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

// 假设这是一个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('正常处理...')
  }
}

是不是很棒!!!666

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值