英文:
eslint no-useless-return in Promise
问题
我刚刚意识到 eslint 的 no-useless-returns 在我写以下内容时发出警告...
```javascript
const success = await new Promise((resolve, reject) => {
let timer = setTimeout(() => {
reject();
return; // <----
}, 5000);
pubs.on('ok', () => {
console.log('okey!');
clearTimeout(timer);
resolve(true);
});
});
现在我明白这个规则想要告诉我的是什么,但据我所知,即使 promise 被拒绝,代码执行也会继续,对吗?那么为什么这被认为是一个无用的返回?
<details>
<summary>英文:</summary>
I just realised that eslint's no-useless-returns is yelling at me for writing the following...
const success = await new Promise((resolve, reject) => {
let timer = setTimeout(() => {
reject();
return; // <----
}, 5000);
pubs.on('ok', () => {
console.log('okey!');
clearTimeout(timer);
resolve(true);
});
});
Now I understand what the rule is supposed to tell me, however afaik code execution would continue even after the promise rejected, right? So why is this considered an useless return?
</details>
# 答案1
**得分**: 2
这个`return`与Promise的回调函数无关:
(resolve, reject) => {
// ...
}
它属于传递给`setTimeout`的箭头函数:
() => {
reject();
return;
}
因此,它只退出了该函数,并且由于它是该函数中的最后一条语句并且没有返回任何内容,因此它是无用的。
即使`setTimeout`会使用从该函数返回的值,它仍然是无用的,因为`return;`是唯一的返回语句,返回`undefined`,而没有`return`的函数也会返回`undefined`。
<details>
<summary>英文:</summary>
That `return` is not related callback function of the Promise:
(resolve, reject) => {
// ...
}
It belongs belongs to the arrow function, passed to the `setTimeout`
() => {
reject();
return;
}
and for that reason, only exits that function, and being the last statement in that function and not returning anything it is useless.
Even if `setTimeout` would do something with the value returned from that function, it would still be useless because `return;` is the only return statement, returns `undefined` and a function without a `return` would also return `undefined`.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论