Подтвердить что ты не робот

Использовать node -redis с node 8 util.promisify

node -v: 8.1.2

Я использую redis client node_redis с node 8 util.promisify, без blurbird.

callback redis.get в порядке, но обещание типа get get

TypeError: Не удается прочитать свойство 'internal_send_command' из undefined
    at get (D:\Github\redis-test\node_modules\redis\lib\commands.js: 62: 24)
    при получении (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)
    в 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();
})()
4b9b3361

Ответ 1

изменение let get = util.promisify(client.get);

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

решил это для меня:)

Ответ 2

Если вы используете узел v8 или выше, вы можете обещать node_redis с помощью 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

Ответ 3

Вы также можете использовать библиотеку 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)