0

I need to assign property failedLoginsNum to one of error properties, but I'm having troubles returning this value from storeFailedLogins(req) function. Here is the function:

function storeFailedLogin(req) {
    var failedLoginsNum; //want to return this value
    req.config.database.find('FailedLogins', {ip:req.connection.remoteAddress})
    .then(function (results) {
        if (!results.length) {
            req.config.database.create('FailedLogins', {
                timestamp: Date.now(),
                failedLoginsNum: 1
            });
            failedLoginsNum = 1;
        } else {
            req.config.database.update('FailedLogins', {ip: req.connection.remoteAddress}, {
                timestamp: Date.now(),
                failedLoginsNum: results[0].failedLoginsNum + 1
            });
            failedLoginsNum++;
        }
    });
    return failedLoginsNum; //trying to return it like that now, but getting undefined
}

And this is how I need to use that property:

var failedLoginsNum = storeFailedLogin(req);
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, {
    message: 'Invalid email address or password.',
    failedLogins: failedLoginsNum
});
snowfinch27
  • 149
  • 2
  • 16
  • Short answer: you cannot. – deceze Aug 03 '16 at 11:17
  • `.then` is inherently asynchronous - use a callback, or preferably, use Promise chains properly – Jaromanda X Aug 03 '16 at 11:17
  • Separately, there are other issues with that code. For instance, in the `else` branch you apply `++` to a variable containing the value `undefined`, which will put the value `NaN` in it. – T.J. Crowder Aug 03 '16 at 11:19
  • if you fix the problem identified by @T.J.Crowder - by initialising failedLoginsNum to 0, I can't see how failedLoginsNum would be anything other than 1 - perhaps the `failedLoginsNum++` should be `failedLoginsNum = results.length + 1` - maybe? – Jaromanda X Aug 03 '16 at 11:23
  • @JaromandaX: Probably it should be `results[0].failedLoginsNum + 1`. – T.J. Crowder Aug 03 '16 at 11:25
  • yes, that sounds right @T.J.Crowder - even given that, there's a LOT of changes to make, and a total rethink of the last `throw` – Jaromanda X Aug 03 '16 at 11:27

0 Answers0