use node-redis with node 8 util.promisify

前端 未结 3 530
借酒劲吻你
借酒劲吻你 2021-02-05 02:19

node -v : 8.1.2

I use redis client node_redis with node 8 util.promisify , no blurbird.

the callback redis.get is ok, but promisify type get error message

相关标签:
3条回答
  • 2021-02-05 02:45

    You can also use Blue Bird Library plus monkey patching will do the trick for you. For example:

    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)
    
    0 讨论(0)
  • 2021-02-05 02:48

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

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

    solved it for me :)

    0 讨论(0)
  • 2021-02-05 02:55

    If you are using node v8 or higher, you can promisify node_redis with util.promisify as in:

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

    or using async await:

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

    culled shamelessly from redis official repo

    0 讨论(0)
提交回复
热议问题