gpt4 book ai didi

javascript - 如何修复使用从另一个文件导入的函数时出现的 'Unexpected identifier' 错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:29 26 4
gpt4 key购买 nike

I am trying to use a function which I defined in another file and exported it. But when I use it and run the node server it throws the error as shown below.

我在这里做的是语法错误吗?

文件夹的路径是正确的,VSCode 自动完成也给出了 文件的相同文件夹路径。

 'use strict';

const express = require('express'),
dotenv = require('dotenv'),
path = require('path');

dotenv.config({ path: path.join('config', 'dev.env') });
const db_connection = require('./db/db-connection');
db_connection.dbConnection();
const services = require("./services/notes");
const app = express(),
port = process.env.PORT || 3000;
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.render('index', {
notes: await services.getNotes()
});
});
app.listen(port, () => {
console.log(`Server is up and running on port ${port}`);
});

我定义函数的文件是:

 'use strict';
const Notes = require('../models/notes');
async function retrieveNotes() {
const notes = await Notes.find().toArray();
return notes;
}
module.exports = { getNotes: retrieveNotes };
res.render('index', {notes: await services.getNotes()});
^^^^^^^^

SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

最佳答案

“意外标识符”是关键字 await,仅允许在异步函数中使用。

就像 edwin walela 所说,您可以通过更改以下方式使您的 app.get 回调函数异步:

app.get('/', (req, res) => { ...

至:

app.get('/', async (req, res) => { ...

关于javascript - 如何修复使用从另一个文件导入的函数时出现的 'Unexpected identifier' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58572221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com