简体   繁体   中英

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?

You need to use a 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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