Angular的对象上的foreach循环是异步的吗? [英] Is Angular's foreach loop over an object asynchronous?

查看:234
本文介绍了Angular的对象上的foreach循环是异步的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在过去的某个地方读到,angular.foreach是异步的,与循环遍历同步的数组不同.长期以来,我一直在考虑这一点,并采取必要措施避免执行循环之后的代码,直到循环完成所有迭代为止(通过将angular.foreach包装在匿名JavaScript函数中,该函数将调用将要执行的回调)一旦循环完成所有迭代).

I read somewhere in the past that angular.foreach is asynchronous unlike looping over arrays which is synchronous. For a long time I was taking into account this and doing the necessary to avoid executing the code which comes after the loop before it's finishes all its iterations (by wrapping the angular.foreach inside an anonymous JavaScript function which calls a callback which will be executed once the loop finishes all iterations).

(function(callback){
  angular.foreach(..)
  callback();
})(callback)

但是我与一位同事交谈,他不同意angular.foreach是异步的,并且我也找不到该信息,这让我感到困惑.

But I had a conversation with a collegue who didn't agree that angular.foreach is asynchronous and I also couldn't find that information again which makes me confused now.

推荐答案

否.看看文档

此外,如果foreach是异步的,则您的代码将无法工作. 如果foreach是异步的,则在调用foreach之后将立即调用该回调,并将foreach放入事件队列中,该事件队列将在以后的某个时间执行.

Furthermore your code wouldn't work if foreach would be asynchronous. If foreach would be async, the callback would be called immediately after calling foreach and foreach would be put onto the eventqueue which would execute it some time in the future.

JavaScript并发模型没有线程,而是使用了一个事件循环.这意味着每个异步操作都将推送到事件队列上,然后再执行.

Javascripts concurrency model does not have threads but instead uses an eventloop. This means every async operation is pushed onto the eventqueue and executed later.

看看 MDN

这篇关于Angular的对象上的foreach循环是异步的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆