如何使用 Node 从 mysql 正确返回结果? [英] How to properly return a result from mysql with Node?

查看:29
本文介绍了如何使用 Node 从 mysql 正确返回结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中

var stuff_i_want = '';
stuff_i_want = get_info(parm);

还有函数get_info:

And the function get_info:

get_info(data){
      var sql = "SELECT a from b where info = data"
      connection.query(sql, function(err, results){
            if (err){ 
              throw err;
            }
            console.log(results[0].objid); // good
            stuff_i_want = results[0].objid;  // Scope is larger than function
            console.log(stuff_i_want); // Yep. Value assigned..
    }

在更大的范围内

stuff_i_want = null

关于返回 mysql 数据并将其分配给变量,我缺少什么?

What am i missing regarding returning mysql data and assigning it to a variable?

============ 每个亚历克斯建议的新代码

============ New code per Alex suggestion

var parent_id = '';
    get_info(data, cb){
          var sql = "SELECT a from b where info = data"
          connection.query(sql, function(err, results){
                if (err){ 
                  throw err;
                }
                return cb(results[0].objid);  // Scope is larger than function
    }

==== 正在使用的新代码

==== New Code in Use

 get_data(parent_recording, function(result){ 
    parent_id = result;
    console.log("Parent ID: " + parent_id); // Data is delivered
  });

不过

console.log("Parent ID: " + parent_id);

在函数parent_id外作用域为null

In the scope outside the function parent_id is null

推荐答案

您将需要了解使用 javascript 的异步调用和回调,这不是 C#、PHP 等...

You're going to need to get your head around asynchronous calls and callbacks with javascript, this isn't C#, PHP, etc...

以下是使用您的代码的示例:

Here's an example using your code:

function get_info(data, callback){
      
      var sql = "SELECT a from b where info = data";

      connection.query(sql, function(err, results){
            if (err){ 
              throw err;
            }
            console.log(results[0].objid); // good
            stuff_i_want = results[0].objid;  // Scope is larger than function

            return callback(results[0].objid);
    })
}


//usage

var stuff_i_want = '';

 get_info(parm, function(result){
    stuff_i_want = result;

    //rest of your code goes in here
 });

当你调用 get_info 时,它依次调用 connection.query,它接受一个回调(这就是 function(err, results) 是什么
然后将范围传递给此回调,依此类推.

When you call get_info this, in turn, calls connection.query, which takes a callback (that's what function(err, results) is
The scope is then passed to this callback, and so on.

欢迎来到 javascript 回调地狱...

Welcome to javascript callback hell...

当你掌握它的时候很容易,只需要一点点习惯,来自像 C# 之类的东西

It's easy when you get the hang of it, just takes a bit of getting used to, coming from something like C#

这篇关于如何使用 Node 从 mysql 正确返回结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆