@nurdus

Как вернуть promise из redis?

Добрый вечер.
Подскажите, плиз как вернуть promise из строки 1 в строку 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);
  })
);


П.С. проект учебный, поэтому прошу не сильно закидывать камнями, но любым комментариям в части чистоты кодинга приму с радостью ;)
  • Вопрос задан
  • 749 просмотров
Решения вопроса 2
К ответу выше: вместо new Promise можно просто пометить функцию как async — она автоматически вернёт Promise, который будет заполнен по достижении return или throw (но сам Promise будет возвращён сразу же ещё до начала фактического выполнения функции):

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; //Возвратит пользователей, аналог предыдущей строчки
})();

Гуглить по запросу async await.
Ответ написан
0xD34F
@0xD34F
Функция findOrCreate должна возвращать Promise. Насколько я понял, вам нужно что-то такое:

exports.findOrCreate = function findOrCreate(userID, provider){
  return new Promise(function(resolve, reject) {
    client.getAsync('accounts:' + provider + ':' + userID).then((accountID) => {
      if (accountID !== null) {
        client.hgetallAsync('account:' + accountID).then(resolve, reject);
      } else {
        reject();
      }
    }, reject);
  });
};
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы