Answer the question
In order to leave comments, you need to log in
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);
})
);
Answer the question
In order to leave comments, you need to log in
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; //Возвратит пользователей, аналог предыдущей строчки
})();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question