// Import necessary modules
const express = require('express');
const app = express();
// Define an asynchronous route handler
const asyncHandler = fn => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
// Define an asynchronous route using the asyncHandler
app.get('/example', asyncHandler(async (req, res) => {
// Perform asynchronous operations
const result = await someAsyncFunction();
// Send the result in the response
res.json(result);
}));
// Define error handling middleware
app.use((err, req, res, next) => {
// Handle errors and send an appropriate response
res.status(500).json({ error: err.message });
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
// Example asynchronous function
async function someAsyncFunction() {
// Simulate an asynchronous operation
return new Promise(resolve => {
setTimeout(() => {
resolve({ message: 'Async operation completed' });
}, 1000);
});
}