Reputation: 174
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.
Upvotes: 4
Views: 8556
Reputation: 19193
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)
Upvotes: 8
Reputation: 9466
They are synchronous.
See for yourself: _.findWhere, _.matches, _.find, _.findIndex, createIndexFinder. There is no instance of setTimeout
in those functions.
Upvotes: 2
Reputation: 2474
The vast majority of JavaScript is synchronous unless stated otherwise.
Asynchronous functions will have callbacks or return promises. But again the majority of functions / methods in various libraries that have callbacks are not asynchronous.
Upvotes: 0