如題
Nodejs
Router.get("/:id", (req, res) => {
mysqldb.query(....) //1.
res.json(data) //會直接執行這邊,才會回去執行第一行
})
有用asyc和await處理,但還是沒有用,
懇請各位大大解答,謝謝
我知道的 promise
應該長這樣
const Express = require('express');
const app = Express();
const router = Express.Router();
const port = process.env.PORT || 3000;
const sleep = (time) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(true), time);
});
}
router.get('/', async (req, res) => {
await sleep(3000);
res.status(200).send({ message: 'Echo after 3 second' });
});
app.use(router);
app.listen(port, () => {
console.log(`Server is running on ${port}`);
});