简体   繁体   English

在应用程序框架中处理异步 Javascript 代码的最佳实践

[英]Best practice for handling async Javascript code in a application framework

I am trying to build a web application, where I have abstracted logic in a Javascript controller class.我正在尝试构建一个 Web 应用程序,其中我在 Javascript 控制器类中抽象了逻辑。 I want to minimize function calls outside of that class.我想尽量减少该类之外的函数调用。

Once in a page in my application, whenever a user performs a task, I want the mark a previous action as completed on my server.一旦进入我的应用程序的页面,每当用户执行任务时,我都希望在我的服务器上将上一个操作标记为已完成。 So I call a method in my Javascript class eg EndTask(id) , which in turn sends out an ajax command to the server.所以我在我的 Javascript 类中调用了一个方法,例如EndTask(id) ,它又向服务器发送了一个 ajax 命令。 No I want to wait for a response to my ajax command before allowing the user to proceed further.不,我想在允许用户继续之前等待对我的 ajax 命令的响应。

I also want to ensure that my Javascript API is kept to a minimum and the page do not have to register any callback.我还想确保我的 Javascript API 保持在最低限度,并且页面不必注册任何回调。

So in essence, I would like to call just EndTask() , and when the function returns, the page would understand that the whole process of marking the task as completed has been performed.所以本质上,我只想调用EndTask() ,当函数返回时,页面会明白将任务标记为已完成的整个过程已经执行。

Is there any way to do this in Javascript, without marking the ajax call as synchronous?有没有办法在 Javascript 中执行此操作,而不将 ajax 调用标记为同步?

It is possible to make an asynchronous function synchronous in JavaScript but to do so you would need to make use of generators which are currently only supported by Firefox.可以在 JavaScript 中使异步函数同步,但要做到这一点,您需要使用目前仅 Firefox 支持的生成器。

I would suggest that you synchronous AJAX calls and fall back on generators in Firefox since it doesn't support synchronous XMLHttpRequest objects.我建议您在 Firefox 中使用同步 AJAX 调用和生成器,因为它不支持同步XMLHttpRequest对象。 Beware however that this might lead to redundancy in your code.但是请注意,这可能会导致代码冗余。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM