首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么不将DB查询的移动结果推入变量?

问为什么不将DB查询的移动结果推入变量?
EN

Stack Overflow用户
提问于 2017-03-25 20:42:27
回答 2查看 42关注 0票数 0

意图

在我的路由中与DB建立连接,运行查询,捕获结果,并使我的索引视图可以在DOM中呈现它。

问题

DB在控制台中成功地连接和返回结果。但是,未能将此结果推入"finalResult“数组。

代码语言:javascript
复制
var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {

// Establish Connection with Database
var mysql = require('mysql');
var connection = mysql.createConnection({
    host : '127.0.0.1',
    user : 'root',
    password : 'xxxxxxx',
    database : 'my_db'
});

connection.connect();

// // Query and post result to console
connection.query('SELECT * FROM products', function(error, results, fields) {
    if (error) throw error;
    doSomething(results[0]);
});

connection.end();


var finalResult = ['hello'];

function doSomething(results) {
    console.log(results.name);
    finalResult.push(results.name);
}

console.log(finalResult);


// Render/make accessible to views
res.render('index', {
    pageTitle: 'Home',
    result: finalResult
});
});

module.exports = router;

doSomething(results[0]);成功地将结果推入doSomething()函数,因为console.log(results.name)返回正确的查询结果。finalResult.push(results.name)会出现问题,因为console.log(finalResult)只返回带有"hello“的数组,而数组应该有"hello”加上查询结果。

EN

回答 2

Stack Overflow用户

发布于 2021-05-27 19:02:59

请注意,当您从mysql模块查询数据库时是同步的(查询以函数作为参数-回调)。这意味着您不能将结果值作为查询函数之外的变量。尝试使用异步/等待或承诺获得返回的值。

票数 1
EN

Stack Overflow用户

发布于 2017-03-25 21:06:19

在将新数据推送到console.log数组之后,尝试在doSomething函数中写入doSomething( finalResult )。

我认为您只看到"helo“,因为console.log( finalResult )在doSomething函数完成之前执行(在将数据添加到finalResult数组之前)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43021750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档