Nodejs MySQL连接查询返回值以调用函数

编程入门 行业动态 更新时间:2024-10-28 13:25:24
本文介绍了Nodejs MySQL连接查询返回值以调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从数据库中获取价值.用一个演示示例进行尝试.但是我在使用回调函数尝试同步调用时遇到问题.我是node.js的初学者,所以不知道这是正确的方法.

I am trying get value from database. Trying it out with a demo example. But I am having problem to synchronize the calls, tried using callback function. I am beginner in node.js, so don't know if this is the right way.

文件1:app.js

FILE 1 : app.js

var data; var db = require('./db.js'); var query = 'SELECT 1 + 1 AS solution'; var r = db.demo(query, function(result) { data = result; }); console.log( 'Data : ' + data);

文件2:db.js

var mysql = require('./node_modules/mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'root', }); module.exports.demo = function(queryString, callback) { try { connection.connect(); console.log('Step 1'); connection.query(queryString, function(err, rows, fields) { console.log('Step 2'); if (err) { console.log("ERROR : " + err); } console.log('The solution is: ', rows[0].solution); callback(rows[0].solution); return rows[0].solution; }); callback(); connection.end(); console.log('Step 3'); } catch(ex) { console.log("EXCEPTION : " + ex); } };

输出:

Step 1 Step 3 Data : undefined Step 2 The solution is: 2

也提到了这个问题,但是并没有解决我的问题: nodeJS从回调返回值

Referred to this question also, but it didnt solve my problem : nodeJS return value from callback

推荐答案

问题是这样的:

var r = db.demo(query, function(result) { data = result; }); console.log( 'Data : ' + data);

console.log将在调用回调函数之前运行,因为db.demo是异步的,这意味着可能要花一些时间才能完成,但是始终将代码的下一行console.log被执行.

The console.log will run before the callback function gets called, because db.demo is asynchronous, meaning that it might take some time to finish, but all the while the next line of the code, console.log, will be executed.

如果要访问结果,则需要等待回调函数被调用:

If you want to access the results, you need to wait for the callback function to be called:

var r = db.demo(query, function(result) { console.log( 'Data : ' + result); });

这是大多数处理I/O的代码将在Node中起作用的方式,因此了解它非常重要.

This is how most code dealing with I/O will function in Node, so it's important to learn about it.

更多推荐

Nodejs MySQL连接查询返回值以调用函数

本文发布于:2023-10-26 14:44:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530451.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值   Nodejs   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!