Javascript 语句周围的括号(不是 IIFE)

Javascript parentheses around statements (not IIFE)

最近学习了一个JavaScript的新技巧,我不太明白。

我知道在像这样使用 fat arrrow / lambda 表达式时需要在对象周围放置 ( ):

示例:

fetch(..).then((response) => ({ data: response } ))

但是为什么这也有效:

const text = (await fetch(...).then(response => response.text()))

因为如果你愿意

const text = await fetch(...)...

你显然得到了 [object Promise]。

很想知道为什么会这样。我一直在尝试 Google 这个,但只是偶然发现了 IIFE,但这就像 (....)();最后加上额外的 ()。

(response) => ({data: response}) 将 return 一个对象 属性 data 设置为响应对象。 response => response.text() 会 return 一个承诺。如评论所述,当在箭头函数中使用单个参数时,括号是可选的。

括号内:

const text = (await fetch(...).then(response => response.text()));

被称为grouping operator and are normally used to change the default precedence。文档使用了一个很好的例子:

var a = 1;
var b = 2;
var c = 3;

// default precedence
a + b * c     // 7
// evaluated by default like this
a + (b * c)   // 7

// now overriding precedence
// addition before multiplication
(a + b) * c   // 9

// which is equivalent to
a * c + b * c // 9

然而,您可以在不需要它们时轻松地使用它们。

var a = 1;
var a = (1);
var a = ((1));

上面的所有行都完全相同。回到您的代码,以下几行是等效的:

var text = await fetch(...).then(response => response.text());
var text = (await fetch(...).then(response => response.text()));

它们在以下情况下确实有所作为:

var text = await promise.toUpperCase();
var text = (await promise).toUpperCase();

第一行将在 promise 上调用 toUpperCase,然后 await toUpperCase 的结果。由于 promise 没有方法 toUpperCase 它会崩溃。

第二行将首先 await promise 结果,然后对结果值调用 toUpperCase。哪个工作得很好(假设承诺解析为一个字符串)。