Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

前端如何优雅的书写请求回调?

// 表单提交
async function formSubmit(form) {
  let response = await Http_request({
    ...form
  });
  if (response.code < 0) {
    this.error(response.code); // 错误消息提示
    // ... 错误处理
  } else {
    this.success(response.code); // 成功消息提示
    // ... 成功处理
  }
}

怎样避免总是出现if(response){...}else{...}这种略显笨拙的写法。因为当一个文件内有好几个请求,每个请求内部的错误处理和成功处理都做着基本没有太大差异的工作的时候,我每次都要重复这种无聊的写法,这很痛苦。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const onResponse = ({ code }) =>
  code < 0 ? this.error(code) : this.success(code);
  
const handleRes = (thenable, onResponse) =>
  thenable.then(onResponse).catch(console.log);

async function formSubmit() {
  await handleRes(
    Http_request({
      ...form,
    }),
    onResponse
  );
}

局部处理可以自己写类似的工具函数。全局处理可以考虑借鉴楼上大佬的思路在 axios 的拦截器统一处理,当然这一部分涉及全局拦截,所以要和团队协调好,不过看你没有 try...catch 应该是拦截器里有人在拦截器里做过了部分异常捕获。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...