我希望在数据到达时发送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?
更多推荐
发布评论