node.js - 从回调函数中获取数据

时间:2013-03-31 09:15:10

标签: javascript node.js

我的node.js代码如下:

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

但它什么都不打印。为什么这样?以及如何从回调函数中获取数据?

非常感谢。

4 个答案:

答案 0 :(得分:3)

你的redis客户端传递一个回调,稍后会调用(当数据通过网络返回时),但是在进行redis调用之后,你正试图在redis向你发送值之前打印该值。你需要等待redis返回一个值。

试试这个

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

答案 1 :(得分:0)

您的redis绑定的client.get函数是异步的。

完成查询redis服务器后会调用回调函数。你应该在回调中打印输出。

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

答案 2 :(得分:0)

文档在Callback之外回答Redis数据

   `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', value);`

我认为这很简单,因为它很简单:)

答案 3 :(得分:0)

粘贴我的 Redis 文件,将回调转换为承诺,以防万一。它在打字稿和类型安全中。您应该会收到智能感知和自动完成功能。

build: {
    transpile: [
        'vee-validate'
    ]
},

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 GET_ASYNC 导入所需的文件,您可以像使用 promise 一样将其与 async-await 一起使用。