N
N
nurdus2017-09-17 22:19:20
Redis
nurdus, 2017-09-17 22:19:20

How to return a promise from redis?

Good evening.
Please tell me how to return a promise from line 1 to line 2.

// account.js
let redis = require('redis'), 
bluebird = require('bluebird');
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
let client = redis.createClient();

exports.findOrCreate = function findOrCreate(userID, provider){
  client.getAsync('accounts:' + provider + ':' + userID).then((accountID) => {
    if (accountID !== null) {
      return client.hgetallAsync('account:' + accountID); // 1
    }
  })
};

// passport.js
let passport = require('passport'),
account = require('./account'),
VKontakteStrategy = require('passport-vkontakte').Strategy;
//...
passport.use(new VKontakteStrategy(config,	
  verify = (accessToken, refreshToken, params, profile, done) => {
    account.findOrCreate(profile.id, profile.provider) // 2
      .then((accountInfo) => { 
        done(null, profile); // done(null, accountInfo);
      })
      .catch(done);
  })
);

P.S. the project is educational, so please do not throw stones too much, but I will gladly accept any comments regarding the cleanliness of coding;)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vitaliy2, 2017-10-15
@nurdus

To the answer above: instead of new Promise, you can simply mark the function as async - it will automatically return a Promise, which will be filled when return or throw is reached (but the Promise itself will be returned immediately before the actual execution of the function begins):

exports.findOrCreate = async function findOrCreate(userID, provider){
    const accountID = await client.getAsync('accounts:' + provider + ':' + userID);
    
    if (accountID !== null) {
        return client.hgetallAsync('account:' + accountID); // 1
    }else{
        throw 'user not found';
    }
};

(async () => {
    const promise = findOrCreate(1); //Возвратит promise
    const users = await findOrCreate(1); //Возвратит пользователей
    const users = await promise; //Возвратит пользователей, аналог предыдущей строчки
})();

Google for async await.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question