在Javascript中组合$.when和async/await
在我的lagacy代码中,我使用jQuery的$.when().then()模式。在when中,两个web调用并行运行。在第一部分中,我现在需要事先访问一些附加数据。我基本上是通过使done处理程序异步并等待web调用来实现的。下面是一个简化的示例:在Javascript中组合$.when和async/await,javascript,jquery,async-await,.when,Javascript,Jquery,Async Await,.when,在我的lagacy代码中,我使用jQuery的$.when().then()模式。在when中,两个web调用并行运行。在第一部分中,我现在需要事先访问一些附加数据。我基本上是通过使done处理程序异步并等待web调用来实现的。下面是一个简化的示例: $.when( firstCall().done(async function(outerData) { let innerData = await anotherWebCall(); doSomeOtherStuff(out
$.when(
firstCall().done(async function(outerData) {
let innerData = await anotherWebCall();
doSomeOtherStuff(outerData, innerData);
console.log('first call finished');
}),
secondCall().done(() => doSomethingElse())
).then(function() {
console.log('everything finished');
});
我希望在控制台中首先看到“FirstCallFinished”,然后看到“everything finished”。然而,情况正好相反。如何解决这个问题?我找到了以下解决方法。我仍然不认为这是一个最佳的解决方案。
const firstCallFinished = $.Deferred();
$.when(
firstCallFinished,
firstCall().done(async function(outerData) {
let innerData = await anotherWebCall();
doSomeOtherStuff(outerData, innerData);
console.log('first call finished');
firstCallFinished.resolve();
}),
secondCall().done(() => doSomethingElse())
).then(function() {
console.log('everything finished');
});