最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js -- get data out of a callback function - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Mar 31, 2013 at 9:15 jackiejackie 852 silver badges8 bronze badges 2
  • Have a look at the first part of my answer here: stackoverflow./a/14220323/218196. It tries to explain the the differences between synchronous and asynchronous code. – Felix Kling Commented Mar 31, 2013 at 9:22
  • this post also might help:: stackoverflow./questions/14110798/… – Sudhir Bastakoti Commented Mar 31, 2013 at 9:23
Add a ment  | 

4 Answers 4

Reset to default 4

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);
       

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);
});

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 autoplete.

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.

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

It'll call callback function after it pletes 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);
});
发布评论

评论列表(0)

  1. 暂无评论