简体   繁体   English

返回变量 MySQL 的 NodeJS 问题

[英]NodeJS problem with returning variable MySQL

function status(s) {
    const n = parseInt(s.substr(1));
    var o = '';
    switch(s[0]) {
        case 'c':
            c.query("SELECT * FROM chapters WHERE id='"+n+"' LIMIT 1", function(e, r) {
                if (e) throw e;
                o = r[0].t;
            });
            break;
    };
    return o;
};

console.log(status('c1'));

How to make this returning variable 'o' from function inside query?如何在查询中从 function 中创建此返回变量“o”?

You need to use a Promise.您需要使用 Promise。 Here is an example.这是一个例子。 I've also refactored the program flow control to the functional level:我还将程序流控制重构为功能级别:

const makeQuery = s => 
    `SELECT * FROM chapters WHERE id='${parseInt(s.substr(1))}' LIMIT 1`

const doQuery = s => new Promise((resolve, reject) => c.query(
               makeQuery(s), 
               (e, r) => e ? reject(e) : resolve(r[0].t)));

const status = s => 
     s[0] === 'c' ? 
        doQuery(s) : 
        Promise.resolve(undefined)

status('c1').then(console.log);

You can do the same thing using async and await , if the query function has a Promise interface in addition to the error-first callback one that you are using at the moment.如果查询 function 具有 Promise 接口以及您目前使用的错误优先回调接口,则您可以使用asyncawait执行相同的操作。

Okay, thanks a lot.好的,非常感谢。 I've rewritten all the code so that it sends two requests, the second one after receiving the data from the first one, and kicked this function out, but it's very possible that I might need to understand this in the future.我已经重写了所有代码,以便它发送两个请求,第二个请求是在接收到第一个请求的数据后,然后将这个 function 踢出去,但很可能我将来可能需要了解这一点。

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

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