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

标签 javascript node.js

我的 node.js 代码是这样的:

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

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

非常感谢。

最佳答案

来自 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 outside the callback is', value);
       

关于javascript - node.js -- 从回调函数中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15728041/

相关文章:

javascript - 这个范围随着继承而丢失

javascript - JS函数不显示任何东西

javascript - 当没有服务器可用于处理请求时,Node.js 需要更好地理解 http.request 操作

node.js - require().server.要求语句中带点

javascript - 在 Async Await 函数中抛出错误后停止执行代码

node.js - Vue-Cli 不会安装

node.js - 谷歌健身 : API gets only details of datasources but not the details of calories in nodejs

javascript - 尝试将元素保持在屏幕中央但包含在父元素中

javascript - 使用 Set 时取消选中项目不起作用

javascript - 单击时更改 div 的样式,并在单击另一个 div 时将其更改回