Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do underscore.js functions, such as _.findWhere(), return results synchronously?

I was using _.findWhere() in underscore.js to find an object containing a specific property from a collection of such objects. For example:

var rules = _.findWhere(rules, {id: ruleId});
if (!rules) {
    // do something 
}
else {
    // do something else
}

Then I started to worry about JavaScript being asynchronous. Do I know that _.findWhere() will finish populating the rules object by the time the second line is executed? Is this something that I need to consider for every method in underscore.js?

I found an answer that says _.each() is synchronous, but I'm not sure how that was determined, nor am I sure if that answer applies for _.findWhere() or other underscore.js functions.

like image 491
drake Avatar asked Dec 24 '22 23:12

drake


1 Answers

I believe every single function of underscore.js is synchronous, so you don't need to worry about it: every line written after it will be executed after.

Anyway, if it was not synchronous (i.e. asynchronous) it would require a callback, such as

// DISCLAIMER: this is a fictionnal code, it is in fact synchronous
_.findWhere(rules, {id: ruleId}, function done() {
    // code to be executed once finished
});

If you're still in doubt, you can just test in your browser's console _.findWhere([{a:true},{a:false}], {a:true}): if you see a result in the console then it was synchronous (note that I'm not familiar with underscore so not sure about my test-example)

like image 95
floribon Avatar answered Dec 27 '22 12:12

floribon