Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some concern about the functions in underscore.js being async or sync

I have been writing code like this, and it works fine.

var result = _.filter(array, function(item){return item[key] === k;});
... // logic using the variable result

but today I suddenly realized technically this could be wrong since the filter could run asynchronously and result could not be available in the code below the filter line.

Is the filter function implemented in sync way? Or do I have to keep it in mind that filter function runs asynchronously?

Thanks in advance!

like image 893
zs2020 Avatar asked Feb 20 '13 18:02

zs2020


1 Answers

You can have a look at the source code [github]:

// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
  var results = [];
  if (obj == null) return results;
  if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
  each(obj, function(value, index, list) {
    if (iterator.call(context, value, index, list)) results[results.length] = value;
  });
  return results;
};

Long story short: _.filter is synchronous and expects the callback function to be synchronous as well (if (iterator.call(context, value, index, list))).

Even more so, the function delegates to the native .filter [MDN] function, which is synchronous as well.


Not every function that accepts a callback must be asynchronous!

like image 104
Felix Kling Avatar answered Sep 29 '22 09:09

Felix Kling