【问题标题】:Multiple function call on button click synchronously with async-await not working按钮单击时的多个函数调用与异步等待不工作同步
【发布时间】:2020-08-05 17:54:47
【问题描述】:

我想弄清楚如何通过 1 个按钮同步单击来调用多个方法。我的第一个函数是 AJAX 调用。所以自然不是同步的。为了解决这个问题,我使用了 async-await。 Async-await 在同一个函数内等待,但不在正在调用的其他函数上。

我正在使用 Stimulus.js 创建类,但一般答案对我来说就足够了:https://stimulusjs.org/

这是我的代码的样子:

按钮:onClick:

classA#methodA classB#methodB

A类

async methodA(event){
  const response = await axios.post('/url', { data }, options);
  const data = await response.json();
  doSomething()
}

B 类

methodB(){
  updateThings()
}

所以我想要实现的是classA#methodA classB#methodB被同步调用。但是即使methodA没有竞争,methodA也不会等待methodB。甚至当我在 methodA 上使用异步等待时。

知道如何解决这个问题吗?

由于 Stimulus.js 的工作方式,创建包装器方法并调用它们似乎是不可能的。

【问题讨论】:

    标签: javascript asynchronous async-await


    【解决方案1】:

    在你的按钮点击中,你应该有类似的东西:

    async () => {
        await methodA();
        await methodB();
    }
    

    而且,这两种方法都应该有async 标记:

    async methodA(event){
      const response = await axios.post('/url', { data }, options);
      const data = await response.json();
      doSomething()
    }
    
    async methodB(){
      updateThings()
    }
    

    由于您的 methodA 是异步的,因此默认情况下对该方法的主要调用不会等待它完成,然后再执行下一行。所以你应该明确地说await methodA()。

    检查一下: Understanding async await in javascript

    【讨论】:

    • 感谢您的回答,但由于 Stimulus.js 无法使用包装方法。
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2020-07-13
    • 1970-01-01
    • 2018-04-23
    相关资源
    最近更新 更多