Node.js 如何在nodejs中通过shell运行时等待异步函数
我有一份档案 demo.js 使用这样一个函数等待从DB获取数据Node.js 如何在nodejs中通过shell运行时等待异步函数,node.js,command-line,async-await,Node.js,Command Line,Async Await,我有一份档案 demo.js 使用这样一个函数等待从DB获取数据 exports.findNames = async () => { const names= await Student.find(); console.log('Names:', names); return names; }; 因此,当我通过shell/命令行测试此函数时,它不会等待函数完成 像这样测试 节点。/demo findNames 注:学生是一个榜样, 从另一个文件发送响应,这就是为什么不在这里。
exports.findNames = async () => {
const names= await Student.find();
console.log('Names:', names);
return names;
};
因此,当我通过shell/命令行测试此函数时,它不会等待函数完成像这样测试
节点。/demo findNames
注:学生是一个榜样,
从另一个文件发送响应,这就是为什么不在这里。而且它不是一个中间件。Mongoose用作数据库工具您需要等待或
。然后
在您的demo.js
中调用函数。让我举个例子:
names.js
exports.findNames = async () => {
const names= await new Promise((res,rej)=>{
setTimeout(()=>{
res([1,2,3])
}, 100);
});
console.log('Names:', names);
};
const name = require('./names');
(async ()=>{
await name.findNames();
})();
demo.js
exports.findNames = async () => {
const names= await new Promise((res,rej)=>{
setTimeout(()=>{
res([1,2,3])
}, 100);
});
console.log('Names:', names);
};
const name = require('./names');
(async ()=>{
await name.findNames();
})();
输出
$ node demo.js
Names: [ 1, 2, 3 ]
你的demo js代码是什么?这是一个简单的nodejs文件,用于使用mongoose从db获取学生详细信息。你的demo.js代码有问题。请把它贴在这里,因为这个例子很有效。用相关信息更新了代码。从另一个文件发送,这就是为什么不在这里。而且它不是一个中间件。你需要有一个像my
demo.js这样的驱动函数来调用你的findNames
函数