AmirA
AmirA

Reputation: 322

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

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.

Upvotes: 4

Views: 1769

Answers (1)

nicholaswmin
nicholaswmin

Reputation: 22949

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.

Upvotes: 12

Related Questions