简体   繁体   中英

Node js redis - undefined variable

does not return when I call the function

function getSportId(lang, name, betcoid){
    redisClient.select(1, function(err,res){
        redisClient.get(lang+"_"+name, function (err, r) {
            let data = JSON.parse(r);
            return "xxx";
        });
    });
}
var print = getSportId(a,b,c);
console.log(print);

Console print return empty:/

According to the documentation

Note that the API is entirely asynchronous. To get data back from the server, you'll need to use a callback.

Node Redis currently doesn't natively support promises (this is coming in v4), however you can wrap the methods you want to use with promises using the built-in Node.js util.promisify method on Node.js >= v8;

const redis = require("redis");
const redisClient = redis.createClient();
const util = require('util');
util.promisify(redisClient.get).bind(redisClient);

function getSportId (lang, name, betcoid) {
    return redisClient.select(1, function (err, res) {
        redisClient.get(lang + "_" + name, function (err, r) {
            console.log(r);
        });
    });
}

getSportId('my', 'foo')

Also be careful about selecting database 1 . The default is 0 . The following will work if you don't have to select 1 .

function getSportId (lang, name, betcoid) {
    redisClient.get(lang + "_" + name, function (err, r) {
        console.log(r); //implement your callback
    });
}

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