首页 > 解决方案 > 如何在nodejs中通过shell运行时等待异步函数

问题描述

我有一个文件

演示.js

使用一个等待从数据库中获取数据的函数,就像这样

exports.findNames = async () => {
  const names= await Student.find();
  console.log('Names:', names);
  return names;
};

所以,当我通过 shell/命令行测试这个函数时,它不等待函数完成。

像这样测试

node ./demo findNames

注意:学生是一个模型,从另一个文件发送响应,这就是为什么不在这里。它不是中间件。Mongoose 用作数据库工具

标签: node.jscommand-lineasync-await

解决方案


您需要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 ]

推荐阅读