0

Problem

Why doesn't the following async arrow function work in Node? It works fine if I define the function and then execute it separately, but not when I do it inline. I know that top-level await and then/catch would suffice. I'm just confused as to why this doesn't work.

See below for code and the error.

const express = require('express')
const mongoose = require('mongoose')

const db = 'file-storage'; const pw = 'fakepassword'

const app = express()

(async () => {
  await mongoose.connect(
    `mongodb+srv://sailor:${pw}@sm-cluster.yldyivh.mongodb.net/${db}?retryWrites=true&w=majority`
  )
  console.log(`Connected to MongoDB @ ${db}`)
})()

The error

TypeError: Cannot read properties of undefined (reading 'headersSent')

    at headersSent (/Users/sailormetz/Software Development/Javascript/CurrentProjects/file-storage/server/node_modules/finalhandler/index.js:256:21)
    at /Users/sailormetz/Software Development/Javascript/CurrentProjects/file-storage/server/node_modules/finalhandler/index.js:92:17
    at Function.handle (/Users/sailormetz/Software Development/Javascript/CurrentProjects/file-storage/server/node_modules/express/lib/application.js:177:5)
    at app (/Users/sailormetz/Software Development/Javascript/CurrentProjects/file-storage/server/node_modules/express/lib/express.js:39:9)
    at Object.<anonymous> (/Users/sailormetz/Software Development/Javascript/CurrentProjects/file-storage/server/app.js:8:1)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
rolias4031
  • 233
  • 2
  • 10
  • Can you provide the working code, i.e. "It works fine if I define the function and then execute it separately" (and make sure it works before [edit](https://stackoverflow.com/posts/72651732/edit)ing your question) – Samathingamajig Jun 16 '22 at 20:53
  • 3
    If *this* is your code, then the problem is that you omitted the semicolon at the end of `express()` and as such fell victim to the ASI rules: [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](https://stackoverflow.com/q/2846283) – VLAZ Jun 16 '22 at 20:59
  • Try adding a `;` after express() – user3094755 Jun 16 '22 at 21:02

0 Answers0