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

Viewed 1331

Running simple script. Got an error.

const fetch = require("node-fetch")
const url = "https://www.someurl.com"

(async ()=>{
    const response = await fetch(url)
    const data = await response
    console.log(data)
})()

ERROR

$ node api.js TypeError: require(...)(...) is not a function

What am I missing here ? Thank you.

1 Answers

Automatic Semicolon Insertion(ASI) doesn't work as you expect it to in some cases.

IIFEs fall into one of those cases, where the parentheses are concatenated with previous line code.

To ameliorate this, just prefix your IIFE's with a semicolon:

const fetch = require("node-fetch")
const url = "https://www.someurl.com"

;(async () => {
    const response = await fetch(url)
    console.log(response)
})()

Or as @estus suggests in the comments, just avoid writing semicolon-less code.

Related