为什么在Node.js Express中未定义变量 [英] Why Variable is undefined in nodejs express

查看:62
本文介绍了为什么在Node.js Express中未定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node js express并从控制器中调用模型.当我调用模型表单控制器并在result变量中获取结果并将其打印在 console.log(result)中时,它是未定义.

I am using node js express and calling model from the controller.When I call model form controller and getting a result in result variable and print it in console.log(result) it's undefined.

控制器

var user_model=require('../models/user');

exports.get_user = function(req, res) {

    var result = user_model.get_users();

    console.log(result);
}

模型

var connection=require('../config/connection');

exports.get_users = function() {

    connection.query('SELECT * FROM users', function(err, rows) {
        if(err) {
            retrun err;
        }
        return rows;
    });
}

推荐答案

之所以会发生这种情况,是因为您在查询完成之前正在安慰结果.节点是异步的.与php节点不同,在进入下一行之前,不必等待查询完成.

This is happening because you are consoling the result before the query has finished. Node is asynchronous. Unlike php node doesn't wait for the query to finish before going to the next line.

这篇关于为什么在Node.js Express中未定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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