异步/同步的Javascript [英] Asynchronous/Synchronous Javascript

查看:98
本文介绍了异步/同步的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些无法理解同步和异步的Javascript之间的差异,并希望有人能提供一些线索这光。

I'm having some trouble understanding the difference between asynchronous and synchronous Javascript, and was hoping someone could shed some light on this.

我了解Javascript本质上是同步的,但你可以使用异步事件/回调来改变你的程序流程。但是,如果你调用一个函数没有回调包含AJAX会发生什么情况?

I know Javascript is inherently synchronous, but you can use asynchronous events/callbacks to alter your program flow. However, what happens if you call a function with no callback that contains AJAX?

例如,如果我有以下的code,其中foo()包含着一些服务器查询和foobar的()中包含一些输出文本:

For example, if I have the following code, where foo() contains some sort of server query and foobar() contains some output text:

foo();
foobar();

将foobar的()被调用之前FOO的内部逻辑()完成后,或将浏览器等到了foo()调用完全之前foobar的执行()? (这似乎很简单,但我的困惑源于回调和他们是否在所有的情况下控制你的程序流程绝对必要的,也就是说,如果FOO(foobar的)始终是必要的。)

Will foobar() be called before the internal logic in foo() is complete, or will the browser wait until foo() is fully executed before calling foobar()? (This seems simple, but my confusion arises from callbacks and whether or not they are absolutely necessary in all cases to control your program flow, i.e. if foo(foobar) is always necessary.)

另外,如果FOO()包含一个服务器调用,快速执行的客户端,但需要很长的时间在服务器上的过程,是一个回调,我可以让我的程序等到富(唯一的方法)是完全完成执行?

Also, if foo() contains a server call that is quickly executed on the client side but takes a long time on the server to process, is a callback the only way I can make my program wait until foo() is completely done executing?

推荐答案

foobar的()在富(Ajax调用之前,的确会称呼)是完整的......

foobar() will indeed be called before the Ajax call in foo() is complete...

除非,这是回答你的第二个问题,您指定的Ajax调用应该是同步的,这是一种选择。这样做会迫使用户要等到调用完成之前,他们可以做任何事情,所以这通常不是最好的选择。使用回调通常是最好的办法。

Unless, and this is the answer to your second question, you specify that the Ajax call should be synchronous, which is an option. Doing so will force the user to wait until the call completes before they can do anything, so that's usually not the best choice. Using a callback is usually the best approach.

这篇关于异步/同步的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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