Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在nodejs中通过shell运行时等待异步函数_Node.js_Command Line_Async Await - Fatal编程技术网

Node.js 如何在nodejs中通过shell运行时等待异步函数

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 注:学生是一个榜样, 从另一个文件发送响应,这就是为什么不在这里。

我有一份档案

demo.js

使用这样一个函数等待从DB获取数据

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
函数