“eslint no-useless-return in Promise” remains the same in Chinese.

huangapple go评论66阅读模式
英文:

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&#39;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>



huangapple
  • 本文由 发表于 2023年4月11日 04:20:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定