Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 将部分请求由callback改为async函数 #592

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

soundofautumn
Copy link

No description provided.

@BH4HPA
Copy link
Member

BH4HPA commented Oct 21, 2024

修改成async的话是出于什么考量? await不好用于catch exception,不好写重试逻辑,没有catch住的话程序会直接崩掉

@soundofautumn
Copy link
Author

await直接使用try catch就行了啊 async函数本质上返回的就是一个promise,改成这样是因为回调不便于维护

@BH4HPA
Copy link
Member

BH4HPA commented Oct 21, 2024

await直接使用try catch就行了啊 async函数本质上返回的就是一个promise,改成这样是因为回调不便于维护

个人还是比较倾向于 Promise 写法,因为错误可以选择逐级处理或者向外传递,函数的返回值、返回时机也更加明确;另外,你现在你的这个更改,没有对应的顶层错误处理的兜底,甚至还有 res res2 这样的写法,除了改 Promise 为 async 外,没有其他的功能性提交。我不太赞成合并。

  • Promise 写法
do().then(r => {
  // do something with result
}).catch(e => {
  // do something with error 
})
  • Try-Catch 写法
// async function() {
try {
  r = await do();
  // do something with result
} catch (e) {
  // do something with error
}

至于回调不便于维护,我不太理解,是否可以举个例子?

@soundofautumn
Copy link
Author

事实上函数的返回值并没有变化,写成async函数后上层函数照样可以用Promise的.then

至于res,res2,原先使用callback的写法也照样使用了res,r等无意义的变量名,我认为这并没有本质上的差别,如有需要也很容易进行修改

同时作为一个爬虫,本质上只是模拟操作流程,如果请求过程中出现错误,证明当前代码肯定是不适用了,一样需要修改,直接抛出异常给出的堆栈信息也能更好的定位问题。

对于不便于维护,比如fetchAllCourses最后的一堆.catch(reject) reject(r.msg)等,即使使用现代ide也需要一段时间找出对应配对的请求并处理,使用await形式我觉得更容易针对单个请求进行错误处理

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants