简体   繁体   English

解析异步函数时,Promise始终未定义

[英]Promise is always undefined when resolving for async function

I'm doing a database query in an async function, then calling it from another file with a promise . 我正在async函数中进行数据库查询,然后从具有promise另一个文件中调用它。 But the result of the promise is always undefined . promise的结果总是undefined

My db function: 我的db函数:

async function findSomething(id) {
   var query = "my_query";
   connection.query(query);
};

This is how I'm calling it from another file: 这是我从另一个文件中调用它的方式:

DbUtil.findSomething(1).then(function(result, error) {
   if(!error) {
    console.log("the result " + result);
  }
});

The result is always undefined . 结果总是undefined

Note that the calling function, DbUtil.findSomething is called from another file. 请注意,调用函数DbUtil.findSomething是从另一个文件调用的。 I do not want to chain it inside the findSomething() function. 我不想在findSomething()函数中链接它。

What am I missing? 我错过了什么?

You are missing a return statement. 你错过了一个return语句。

Any function without one returns undefined . 没有一个函数的任何函数返回undefined

Since findSomething is as async function, the return value is used to resolve the promise it returns. 由于findSomethingasync函数,因此返回值用于解析它返回的promise。

async function findSomething(id) {
  var query = "my_query";
  return connection.query(query);
};

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

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