V
V
vetsmen2017-01-18 10:39:11
Node.js
vetsmen, 2017-01-18 10:39:11

Asynchrony and taking a request request?

I have a function

var getStore = function(sessionID) {
  sessionStore.get(sessionID, function(err, session){
    return session ? true : false;
  });
};

On which there are 2 questions:
1) It does not work due to the fact that it is asynchronous. How to make it work? On the example with promises, no matter how I tried, they do not work. Can you give a specific example of this code?
2) How to make this function look like: req.getStore() , which will be called like this: socket.request.getStore() , take socket.request.sessionID in it , check in sessionStore and return true/false?
Those. now it looks something like this: getStore(socket.request.sessionID), but I would like socket.request.getStore()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2017-01-18
@vetsmen

Well, why? Why turn good asynchronous code into bad synchronous code? There is a tool - work. Why change it?
Badly tried:

var getStore = function (sessionID) {
    return new Promise(
        function (resolve, reject) {
            sessionStore.get(sessionID, function(err, session) {
                if(err) {
                    reject(err);
                }
                resolve(!!session);
            });
        });
}
// usage
getStore(1).then(function(isAuth){
    // isAuth - true or false
}, function(error){
    // error
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question