node.js - 如何在nodejs中通过shell运行时等待异步函数
问题描述
我有一个文件
演示.js
使用一个等待从数据库中获取数据的函数,就像这样
exports.findNames = async () => {
const names= await Student.find();
console.log('Names:', names);
return names;
};
所以,当我通过 shell/命令行测试这个函数时,它不等待函数完成。
像这样测试
node ./demo findNames
注意:学生是一个模型,从另一个文件发送响应,这就是为什么不在这里。它不是中间件。Mongoose 用作数据库工具
解决方案
您需要await
或.then
您的demo.js
. 让我给你举个例子:
名称.js
exports.findNames = async () => {
const names= await new Promise((res,rej)=>{
setTimeout(()=>{
res([1,2,3])
}, 100);
});
console.log('Names:', names);
};
演示.js
const name = require('./names');
(async ()=>{
await name.findNames();
})();
输出
$ node demo.js
Names: [ 1, 2, 3 ]
推荐阅读
- python - 如何在 Python 中对图例标签进行分组?
- javascript - 在 NodeJs Express 中集成服务器发送的事件
- python - 在 Anaconda 本地运行 github 存储库
- php - 从 PHP 中的多维数组中删除包含键和值的所有单引号时遇到问题
- javascript - 按顺序初始化类
- react-dnd - React-Dnd - 如何控制相对于光标的拖动预览位置并获取相对于放置目标的放置位置
- javascript - 如何使用cordova在后台拨打电话?
- istio - 特使代理使用什么语言?
- django - 我的 linux 服务器中的 Django 和帐户问题
- python - Python:矩形参数无效