简体   繁体   English

Function 在尝试查询 node.js 中的数据库时返回“未定义”

[英]Function returning "undefined" while trying to query database in node.js

This piece of code always returns undefined to the calling function.这段代码总是返回 undefined 给调用 function。 I'm new to JavaScript and I did try and look into some of the callback solutions on Stack Overflow and other resources but none of them worked for me.我是 JavaScript 的新手,我确实尝试研究了 Stack Overflow 和其他资源上的一些回调解决方案,但没有一个对我有用。 Any help with this would be highly appreciated.对此的任何帮助将不胜感激。 Thank you!谢谢!

var funcs = require('./index.js');
var connected = require('./database')

query='SELECT * from trades'
const res = execute_rows(query)
console.log(res)


function execute_rows(query){
 con = connected();
 con.query(query, function(err, result, fields) {
     if (err) {
         return console.log(err);
     }
     console.log(result) //Displays correct results
     return result; // Returns undefined to calling function
 })
 con.end();
}

Harshith哈施特

Ok, if you print de result of your query inside the function execute_rows just before de return statement you should be able to see it.好的,如果您在 de return语句之前的 function execute_rows中打印查询结果,您应该能够看到它。

The problem with your function is your not actually returning the result "on time".您的 function 的问题是您实际上没有“按时”返回结果。 You need to return a promise to get the result from your function.您需要返回 promise 以从 function 中获取结果。

This could be a little hard to understand when you're new in JS.当您是 JS 新手时,这可能有点难以理解。 Your function should be something like this:你的 function 应该是这样的:

function execute_rows(query){
 con = connected();
 return new Promise((resolve, reject) => {
     con.query(query, function(err, result, fields) {
         if (err) {
             // Returning the error
             reject(err);
             con.end();
         }

         resolve(result);
         con.end();
     });
 });
}

Now, when you call you call your function, you have two options:现在,当您打电话给您的 function 时,您有两种选择:

  1. Use async/await使用异步/等待
  2. Still using promises (callback-driven)仍在使用 Promise(回调驱动)

Calling your function:致电您的 function:

const dbResult = await execute_rows(query);

or或者

execute_rows(query).then(result => {
    // Get the result
    console.log('result:', result);
}).catch(error => {
    // Get the error
    console.log('error:', error);
});

Please, read about promises and async/await pattern: Links:请阅读有关promisesasync/await模式的信息:链接:

Promises: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise承诺: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise

Async/await: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await异步/等待: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

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

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