My problem: i have an array with users and an user_hash and need to find the matching user. I came up with the following solution:
//results is the array user objects
//safety_first.getUserHash is a function that calculates a user_hash, it retrieves the user-record based on the id and then combines values of some fields and a key and turns this into a hash.
if (results.length > 0)
{
var i = 0;
function checkUserhash(user_id, user_hash, callback) {
safety_first.getUserHash(user_id, function(check_user_hash) {
if (user_hash == check_user_hash)
{
callback(user_id);
}
else
{
if ((i+1) < results.length)
{
i++;
checkUserhash(results[i].id, user_hash, callback);
}
else
{
callback(false);
}
}
});
}
checkUserhash(results[i].id, user_hash, function(user_id) {
if (user_id)
{
console.log("MATCH: "+user_id);
}
else
{
console.log("NO MATCH");
}
});
}
I first tried to do this in a for-loop but cause it calls the checkUserhash asychronously i could not break the loop when the match was found.
I'm looking for other possible solutions, please share your thoughts.
regards, Pieter
safety_firsta service you could change? E.g. return a promise instead of using a callback?