如何解决JavaScript中的“不是函数”错误

I write JavaScript without semicolons.

我写JavaScript没有分号。

And I really like that. The language is cleaner, in my opinion.

我真的很喜欢。 我认为这门语言比较干净。

You might not like that, and it’s understandable. But that’s the way it is.

您可能不喜欢它,这是可以理解的。 但这就是事实。

Semicolons are optional. We are not required to add them.

分号是可选的。 我们不需要添加它们。

Sometimes, however, we must pay attention. In particular, in Node.js we use require() to load external modules and files.

但是,有时我们必须注意。 特别是在Node.js中,我们使用require()加载外部模块和文件。

This can cause, in some cases, an error like this:

在某些情况下,这可能会导致如下错误:

TypeError: require(...) is not a function

That’s a weird error, right?

那是一个奇怪的错误,对吧?

Let’s look at how I got it.

让我们看看我是怎么得到的。

I required a library, and then I had to run some code at the root level and I created an immediately-invoked async function:

我需要一个库,然后我必须在根级别运行一些代码,然后创建了一个立即调用的异步函数:

const fs = require('fs')

(async () => {
  //...
})()

JS does not see a semicolon after require(), and we start a line with a (, and JS thinks we’re trying to execute a function.

JS在require()之后看不到分号,我们以(开头,而JS认为我们正在尝试执行一个函数。

It consider require('fs') as the name of the function, which is something that could actually work if the module export returned a function.

它将require('fs')作为函数的名称,如果模块导出返回函数,则该函数实际上可以工作。

But it’s not, so we get that ...is not a function error.

但这不是,所以我们得到的...is not a function错误。

How do we fix it?

我们该如何解决?

We must add a semicolon. Somewhere.

我们必须添加一个分号。 某处。

This would work:

这将工作:

const fs = require('fs')

;(async () => {
  //...
})()

and also this would work:

而且这将工作:

const fs = require('fs');

(async () => {
  //...
})()

It’s a little price we have to pay to avoid the use of semicolons everywhere.

为了避免在任何地方使用分号,我们必须付出一点代价。

Tip: top-level await is now a thing, you can use that instead of this structure, and it will prevent such errors.

提示:现在顶层等待已成为现实,您可以使用它来代替此结构,这样可以防止此类错误。

翻译自: https://flaviocopes.com/is-not-a-function/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值