kissues
kissues

Reputation: 245

Top level await not working for Node 16.16.0?

I am converting my node app to use top level await for connecting to my Redis client but am getting the error "await is only valid in async functions and the top level bodies of modules".

I do not understand why I am getting this error since I am using Node version 16.16.0 and top level await should work for Node.js since v14.8??

Why is my code not working?

Versions used: NODE v16.16.0, Redis ^4.2.0

STACK TRACE

at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/app/git/app-node-api/src/index.js:4:1)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)

CODE

const Redis = require("redis")
const util = require(`util`)
const client = Redis.createClient({
  url: process.env.REDIS_CLIENT_PRIMARY,
})

client.on("error", async (err) => console.log("Redis Client Error", err))

await client.connect() // <- THROWS ERROR "await is only valid in async functions and the top level bodies of modules" 

Upvotes: 2

Views: 3981

Answers (1)

Slava Knyazev
Slava Knyazev

Reputation: 6081

Top-level await is only available in ES modules. You can write a module by using the mjs extension instead of js or by setting { "type": "module" } in package.json.

Upvotes: 4

Related Questions