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)