JavaScript, return promise inside 箭头函数

JavaScript, return promise inside arrow function

我刚看到这段代码:

const buildSW = () => {
  // This will return a Promise <- that comment was present on the code
  workboxBuild
    .injectManifest({
      swSrc: 'src/sw.js'
      // some code
    })
    .then(({ count, size, warnings }) => {
      // some code
    })
    .catch(console.error);
};
buildSW();

代码似乎可以工作,已经投入生产大约 1 年了,但我对 This will return a Promise 的评论感到困惑,因为我没有看到实际上有一个 return 声明,整个代码都在 { } 里面。

不应该?:

return workboxBuild
    .injectManifest({ ...etc

代码是本指南的一部分:

https://developers.google.com/web/tools/workbox/guides/generate-service-worker/workbox-build

那里有 return 承诺。那么上面显示的代码中没有 return 如何或为什么工作?

该评论是对其后一行的评论,是多余的。例如

// a() will return a Promise
a().then(() => () // duh

...因为它等同于:

const promise = a();
promise.then(() => ()

Shouldn't be?: return workboxBuild.injectManifest({ ...etc

这取决于您希望 buildSW 拥有的合同。

如所写,buildSW return什么都没有,并处理自己的错误,使用 .catch(console.error) 将它们发送到控制台。适用于事件处理程序——例如button.onclick = buildSW.

但是如果你希望从其他地方调用buildSW,更好的契约是return一个承诺,并将错误处理留给调用者:

const buildSW = () => {
  return workboxBuild.injectManifest({swSrc: 'src/sw.js'})
    .then(({ count, size, warnings }) => {
      // some code that may also fail
    });
};
buildSW().catch(console.error);

I get confused with the comment because I don't see that there is actually a return statement, like it is present in the guide. Shouldn't it have one?

是的,应该有一个return声明。当然,该函数已经捕获错误并记录它们,但始终 return 来自异步函数的承诺仍然是一个好主意。

So how or why is working without return in the code showed above?

之所以有效,是因为您正在进行的 buildSW(); 调用没有尝试使用应该 returned 的承诺。