将node-redis与节点8一起使用util.promisify

时间:2017-06-29 02:46:06

标签: node.js redis promise

node -v:8.1.2

我使用redis客户端node_redis和节点8 util.promisify,没有blurbird。

回调redis.get没问题,但是promisify类型获取错误消息

  

TypeError:无法读取属性' internal_send_command'未定义的       在get(D:\ Github \ redis-test \ node_modules \ redis \ lib \ commands.js:62:24)
      at get(internal / util.js:229:26)
      在D:\ Github \ redis-test \ app.js:23:27
      在对象。 (d:\ Github上\ redis的测试\ app.js:31:3)
      在Module._compile(module.js:569:30)
      at Object.Module._extensions..js(module.js:580:10)
      在Module.load(module.js:503:32)
      在tryModuleLoad(module.js:466:12)
      在Function.Module._load(module.js:458:3)
      在Function.Module.runMain(module.js:605:10)

我的测试代码

const util = require('util');

var redis = require("redis"),
    client = redis.createClient({
        host: "192.168.99.100",
        port: 32768,
    });

let get = util.promisify(client.get);

(async function () {
    client.set(["aaa", JSON.stringify({
        A: 'a',
        B: 'b',
        C: "C"
    })]);

    client.get("aaa", (err, value) => {
        console.log(`use callback: ${value}`);
    });

    try {
        let value = await get("aaa");
        console.log(`use promisify: ${value}`);
    } catch (e) {
        console.log(`promisify error:`);
        console.log(e);
    }

    client.quit();
})()

3 个答案:

答案 0 :(得分:38)

更改let get = util.promisify(client.get);

let get = util.promisify(client.get).bind(client);

为我解决了这个问题:)

答案 1 :(得分:0)

  

如果您使用的是节点v8或更高版本,则可以使用   util.promisify如下:

const {promisify} = require('util');
const getAsync = promisify(client.get).bind(client); // now getAsync is a promisified version of client.get:

// We expect a value 'foo': 'bar' to be present
// So instead of writing client.get('foo', cb); you have to write:
return getAsync('foo').then(function(res) {
    console.log(res); // => 'bar'
});
     

或使用异步等待:

async myFunc() {
    const res = await getAsync('foo');
    console.log(res);
}

redis official repo

答案 2 :(得分:0)

您还可以使用 Blue Bird 库以及猴子补丁程序来完成此操作。 例如:

const bluebird = require('bluebird')
const redis = require('redis')
async connectToRedis() {
     // use your url to connect to redis
     const url = '//localhost:6379'
     const client = await redis.createClient({
                url: this.url
            }) 
     client.get = bluebird.promisify(client.get).bind(client);
     return client
   }
// To connect to redis server and getting the key from redis
connectToRedis().then(client => client.get(/* Your Key */)).then(console.log)