jackie
jackie

Reputation: 85

node.js -- get data out of a callback function

my node.js code like this:

var data = "";
//redis client
client.get(key,function(err,value){
    data += value;
});
//output
console.log(data);

BUT, it prints nothing. Why so? and how can i get the data out of the callback function?

thanks a lot.

Upvotes: 4

Views: 3486

Answers (4)

Firoj Siddiki
Firoj Siddiki

Reputation: 1941

ANSWER FROM THE DOCUMENTATION for Redis DATA outside the CALLBACK

        const redis = require('redis');
        const redisClient = redis.createClient(process.env.REDIS_URI);

        // using Node.js >= v8 built-in utility
        const { promisify } = require('util');

        // forcing function to return promise
        const getAsync = promisify(redisClient.get).bind(redisClient);
        const value = await getAsync(key);

        console.log('value of redis key outside the callback is', value);
       

Upvotes: 4

Tom Bombadil
Tom Bombadil

Reputation: 3975

Pasting my Redis file that converts callbacks into promises, in case it's helpful. It's in typescript and typesafe. You should receive intellisense and autocomplete.

import redis from "redis"
import { promisify } from "util"
import { redisHost as host, redisPort as port } from "../../configKeys"

const client = redis.createClient({
  port,
  host,
})

client.on("connect", () => {
  console.log(`Redis Client connected on port ${port}`)
})

client.on("ready", () => {
  console.log("Redis Client ready to use..")
})

client.on("error", (err) => {
  console.log(err.message)
})

client.on("end", () => {
  logCommon.debug("Redis Client disconnected")
})

process.on("SIGINT", () => {
  client.quit()
})

export const GET_ASYNC = (promisify<string>(client.GET).bind(
  client
) as unknown) as (key: string) => Promise<string | null>

export const SET_ASYNC = (promisify<string, string, string, number>(
  client.SET
).bind(client) as unknown) as (
  key: string,
  value: string,
  mode: string,
  duration: number
) => Promise<"OK" | null>

export const DELETE_ASYNC = (promisify<string>(client.DEL).bind(
  client
) as unknown) as (key: string) => Promise<number | null>

export default client

Import GET_ASYNC or SET_ASYNC into the required file and you can use it with async-await like you would a promise.

Upvotes: 0

smitrp
smitrp

Reputation: 1312

Your redis binding's client.get function is asynchronous.

It'll call callback function after it completes querying redis server. You should print output in callback.

var data = "";
//redis client
client.get(key,function(err,value){
    data += value;
    //output
    console.log(data);
});

Upvotes: -1

Daniel
Daniel

Reputation: 38781

Your passing the redis client a callback which will be called later (when the data is returned over the network), but then right after making the redis call you're trying to print the value before redis has sent you a value. You need to wait for redis to return a value.

Try this

var data = "";
//redis client
client.get(key,function(err,value){
    data += value;
    //output 
    console.log(data);
});

Upvotes: 2

Related Questions