Some concern about functions in underscore.js that are asynchronous or synchronizing

I am writing code like this and it works great.

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

but today I suddenly realized that this might be wrong, since the filter can work asynchronously, and the result may not be available in the code below the filter line.

Is the filter function implemented synchronously? Or do I need to remember that the filter function is asynchronous?

Thanks in advance!

+5
source share
1 answer

You can see the source code [github] :

// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5** 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;
};

In short: it _.filter is synchronous and expects the callback function to also be synchronous ( if (iterator.call(context, value, index, list))).

, native .filter [MDN], .


, , !

+11

All Articles