admin管理员组文章数量:1323738
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!
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!
Share Improve this question edited Feb 20, 2013 at 18:53 zs2020 asked Feb 20, 2013 at 18:47 zs2020zs2020 54.6k30 gold badges156 silver badges223 bronze badges 01 Answer
Reset to default 12You 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!
本文标签: javascriptSome concern about the functions in underscorejs being async or syncStack Overflow
版权声明:本文标题:javascript - Some concern about the functions in underscore.js being async or sync - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742119983a2421649.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论