简体   繁体   English

使用节点js将mysql结果解析为变量

[英]Parse mysql results into variable with node js

I'm trying my best to understand nodeJS/typescript and it techniques. 我正在尽力了解nodeJS / typescript及其技术。 But still can't figure out how I can save my databasequery result into a variable and return it. 但是仍然不知道如何将数据库查询结果保存到变量中并返回它。 Maybe someone can explain me the problem / help me: 也许有人可以向我解释问题/帮助我:

I have a method like this: 我有这样的方法:

public getAllProducts(): ProductArray {
    // returns IConnection from "mysql" and connect
    this.databaseConnection.getConnection().connect();

    var product: any = [];
    this.databaseConnection.getConnection().query('SELECT * FROM product', function (error: any, results:any, fields:any) {
        if (error) throw error;
        product.push(results);
    });



    console.log(product);
    return product;
}

Would be nice if someone can help me out here. 如果有人可以在这里帮助我会很好。

You are not supposed to be able to return a variable from an async function. 您不应该能够从异步函数返回变量。 You should go ahead and read some articles about how to combat callback hell. 您应该继续阅读一些有关如何应对回调地狱的文章。 All your logic that requires this data should be inside the callback function of the query. 您需要此数据的所有逻辑都应在查询的回调函数内。 Some options to make your code look a little bit better is using the async.js module or promises (you can also check the async/await that was added on nodeSJ 7.6.0 version. 使用async.js模块或promises (使您的代码看起来更好)的一些选项(您还可以检查在nodeSJ 7.6.0版本中添加的async / await。

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

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