Basic async/await question in Next
Unanswered
Virginia's Warbler posted this in #help-forum
Virginia's WarblerOP
This might be a primary school question, but:
Because of this
But, how can I include a
Also, when I run
Because of this
await, there obviously needs to be an async: https://github.com/Ruslan-Aliyev/Next-Tailwind-Typescript/blob/master/src/app/_utils/db.ts#L3 But, how can I include a
async here?Also, when I run
npm run dev, no error happens and all continues well. The error only happens when I run npm run build. Why is that?6 Replies
Brown bear
create an async arrow function that will return the logic.
const db = async () => {
await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
})
}or you can wrap entire logic into an async function
const connectDB = async () => {
const db = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
});
db.on('error', (err) => {
console.log('- STATS Mysql2 connection died:', err);
});
}@Brown bear or you can wrap entire logic into an async function
`const connectDB = async () => {
const db = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
});
db.on('error', (err) => {
console.log('- STATS Mysql2 connection died:', err);
});
}`
Virginia's WarblerOP
But, if I write this way, then how can I export and import
I tried writing this way, then
And when I imported it, I wrote
db?I tried writing this way, then
export default connectDB;And when I imported it, I wrote
import {db} from "../_utils/db.ts"; instead of import db from "../_utils/db.ts";, but that didnt workBrown bear
that's because you've exported the function as a default export.
American Crow
// db.js
const mysql = require('mysql2/promise');
export async function initializeDatabase() {
const db = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
});
db.on('error', (err) => {
console.log('- STATS Mysql2 connection died:', err);
});
return db;
}// Usage in another file
import { initializeDatabase } from './db';
async function someFunction() {
const db = await initializeDatabase();
// Use the db connection
}