简体   繁体   English

我得到 Promise {<pennding> } 在 node.js 异步 function</pennding>

[英]I'm getting Promise { <pennding> } on node.js async function

I have this function on a class on nodejs.我在nodejs上的class上有这个function。 It is getting all rows on DB.它正在获取数据库上的所有行。

module.exports = class fooClass {
  static async fooFunc() {
    const mysql = require('mysql');
    const util = require('util');
    const conn = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '',
      database: 'dbname'
    });

    // node native promisify
    const query = util.promisify(conn.query).bind(conn);

    try {
      const rows = await query('SELECT * FROM `dbtable`');
      return rows;
    } finally {
      conn.end();
    }
  }
}

When I call this function,当我称之为 function 时,

let result = fooClass.fooFunc();
console.log(result);

I am getting this:我得到这个:

Promise { <pennding> }

I can use fooClass.fooFunc().then... but that will require me to add a callback function on then and that will require a lot of changes.我可以使用fooClass.fooFunc().then...但这需要我添加一个回调 function then需要进行大量更改。

Is there any way we can get the rows by just calling let result = fooClass.fooFunc();有什么方法可以通过调用let result = fooClass.fooFunc(); ? ?

Thanks in advance.提前致谢。

When function call is done within a function then you can write it as @Bravo has suggested:当 function 调用在 function 内完成时,您可以按照@Bravo 的建议编写它:

let result = await fooClass.fooFunc();

Link for async/await 异步/等待的链接

If you are calling it outside a function then:如果您在 function 之外调用它,则:

(async function(){
   let result = await fooClass.fooFunc();
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM