简体   繁体   English

链接JavaScript中的异步方法

[英]Chaining asynchronous methods in JavaScript

I'd like to do something like this: 我想做这样的事情:

var res = myAjax.post();

myAjax is basically my own ajax wrapper (asynchroneous). myAjax基本上是我自己的ajax包装器(异步)。 I don't necessary need the chaining, but i'd like to be able to do the call like shown above. 我不需要链接,但是我希望能够进行如上所示的呼叫。 I'd like a callback to be handled by the object itself. 我希望对象本身可以处理回调。 I've read about asynchroneous method queues, but, honestly, couldn't fully understand it. 我已经读过异步方法队列,但是,老实说,我不能完全理解它。 I know i could use a synchroneous ajax call, but it should be possible to do it asynchroneously as well if i understand it correctly. 我知道我可以使用同步ajax调用,但是如果我正确理解的话,也应该可以异步进行。 Any help is very appreciated. 任何帮助都非常感谢。 Thank you. 谢谢。

I've done a demo here that might be something along the lines of what you mean... 我在这里做了一个演示,可能与您的意思类似...

In that demo, there are two types of objects: MyAjax which has the 'post' method as above, and a MyRes object with a getData method that will return null until the async call has successfully completed. 在该演示中,有两种类型的对象: MyAjax其具有与上述“后”的方法,和MyRes与对象getData方法会返回null ,直至异步调用已成功完成。 After it has completed, it will return the data fetched from the ajax call. 完成后,它将返回从ajax调用获取的数据。

In the demo, I have a function checking for the response every second, but the post method also handles a callback which allows you to be notified when the ajax call has completed successfully. 在演示中,我有一个函数每秒检查一次响应,但是post方法还处理一个回调,该回调使ajax调用成功完成时可以得到通知。

I don't know why you'd want to do it this way, but it is doable. 我不知道您为什么要这样做,但这是可行的。

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

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