【问题标题】:Combine $.when and async/await in Javascript在 Javascript 中结合 $.when 和 async/await
【发布时间】:2020-03-30 13:33:58
【问题描述】:

在我的遗留代码中,我使用了 jQuery 的 $.when().then() 模式。在此期间,两个 Web 调用并行运行。在第一个中,我现在需要事先访问一些额外的数据。我基本上试图通过使完成的处理程序异步并等待该网络调用来实现这一点。这是一个简化的示例:

$.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');
});

我希望,我会首先在控制台中看到“第一次通话完成”,然后是“一切都完成”。然而,情况恰恰相反。我该如何解决?

【问题讨论】:

    标签: javascript jquery async-await .when


    【解决方案1】:

    我找到了以下解决方法。我仍然认为这不是最佳解决方案。

    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');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 2021-12-08
      • 1970-01-01
      • 2018-07-18
      • 2015-12-25
      相关资源
      最近更新 更多