混合同步函数和异步延迟jQuery对象(Mix of synchronous functions and asynchronous deferred jQuery objects)

编程入门 行业动态 更新时间:2024-10-09 23:22:08
混合同步函数和异步延迟jQuery对象(Mix of synchronous functions and asynchronous deferred jQuery objects)

我希望在数据到达时发送Ajax请求并执行一些不相关的操作。 完成操作后,我喜欢等待Ajax完成并执行其他操作。

具体来看看剥离的例子:

$.ajax({url: "/reqA"}) .done(updateA) .done($.ajax("/reqB").done(updateB)) .done(updateFinal)

updateFinal应在完成同步updateA和异步/reqB并跟随同步updateB 。

上面的代码是错误的,因为所有后续的.done()操作来自/regA updateB并且在updateB和updateFinal之间发生竞争条件。

我可以用.then修复代码:

$.ajax({url: "/reqA"}) .done(updateA) .then($.ajax("/reqB").done(updateB)) .done(updateFinal)

但接下来我想在发送request /reqB (因为JS引擎单线程和updateA执行阻塞异步进程/reqB !!)后运行updateA 。

以下代码不起作用:

$.ajax({url: "/reqA"}) .then($.ajax("/reqB").done(updateB)) .done(updateA) .done(updateFinal)

因为updateA执行会延迟到updateB执行!!

我认为这个问题可以用$.when updateA函数来解决,但updateA不是承诺,并且我没有在官方$ .when文档中看到执行保证的顺序。 它可能看起来像:

$.ajax({url: "/reqA"}) .then( $.when( $.ajax("/reqB").done(updateB), fakeResolvedPromiseWrapperAroundSyncFunc(updateA) ) ).done(updateFinal)

jQuery库中是否有标准的fakeResolvedPromiseWrapperAroundSyncFunc解决方案?

启动异步并稍后加入异步调用结果后运行同步代码的任何其他路径?

I want to send Ajax request and perform some unrelated actions while data arrived. After finishing actions I like to wait for Ajax finishing and perform another actions.

To be concrete lets see to stripped example:

$.ajax({url: "/reqA"}) .done(updateA) .done($.ajax("/reqB").done(updateB)) .done(updateFinal)

updateFinal should be performed after completion of synchronous updateA and asynchronous /reqB and following synchronous updateB.

Above code is wrong because all subsequent .done() operates on promise from /regA and race condition occur between updateB and updateFinal.

I can fix code with .then:

$.ajax({url: "/reqA"}) .done(updateA) .then($.ajax("/reqB").done(updateB)) .done(updateFinal)

But next I want to run updateA after sending request /reqB (because JS engine single threaded and updateA execution blocked asynchronous process /reqB!!).

Following code doesn't work:

$.ajax({url: "/reqA"}) .then($.ajax("/reqB").done(updateB)) .done(updateA) .done(updateFinal)

because updateA execution will be delayed to updateB execution!!

I think that problem can be solved with $.when function, but updateA isn't promise and I don't see order of execution guaranty in official $.when docs. It could look like:

$.ajax({url: "/reqA"}) .then( $.when( $.ajax("/reqB").done(updateB), fakeResolvedPromiseWrapperAroundSyncFunc(updateA) ) ).done(updateFinal)

Are there any standard fakeResolvedPromiseWrapperAroundSyncFunc solution in jQuery library?

Any other path to run synchronous code after starting asynchronous and later joining to result of async call?

更多推荐

本文发布于:2023-07-30 15:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1338821.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   对象   Mix   synchronous   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!