【问题标题】:Wait for function 2 to execute inside function 1 - javascript等待函数 2 在函数 1 内执行 - javascript
【发布时间】:2019-12-01 02:05:34
【问题描述】:

基本上我有开关盒。在其中,我将不得不执行完全依赖于其他要执行的函数的函数。

Switch(){
    case '1':
        //Executes first always
        function a(){
            ..
            ..
            ..
            b().then(){
                //Execute this block only after function b is executed
            }
            ..
            ..
            .. 
            c().then(){
                //Execute this block only after function c is executed
            }
            ..
            ..
        }
    break;
    case '2':
        function b(){

        }
    break;
    case '3':
        function c(){

        }
    break;
}

在上面的例子中,case '1' 将首先被执行。在里面,我将不得不等待function b() 执行然后继续执行 函数 a()。就像function c() 一样明智。如何做到这一点?

【问题讨论】:

  • Switch(){ 语法不正确,仅声明一个函数不会调用它 - 要调用一个函数,请将 ()s 放在其名称后,例如 a();
  • @CertainPerformance 将是解释的错字。我在 switch 语句中有函数。
  • b 是否返回承诺?如果没有,你就不能使用then(),你只需要把代码按正确的顺序排列,它们就会按照你的意愿执行。
  • 这似乎行不通……你想让这些函数做什么?

标签: javascript function promise wait


【解决方案1】:

您需要链接您的承诺以强制排序。你的伪代码有点混乱。除了switch(val) 的大写,您还声明了一个函数a(),但没有调用它。无论如何,如果您要调用a() 并希望在其中对返回b()c() 的promise 进行排序,您可以这样做:

case '1':
    ..
    a();    // not asynchronous
    ..
    return b().then(c).then(...)
}

这假定a() 不是异步的,并且b()c() 返回的promise 会在它们中的异步操作完成时实现。而且,a() 中没有其他异步操作。

这将在b() 返回的承诺解决时运行c(),然后在c() 返回的承诺解决时调用最后一个.then() 处理程序。

我在这里展示了 Promise 链的 return,以便调用者知道所有这些异步操作何时完成。

如果您希望 switch 语句之后的代码也等待这些完成,因此不使用 return,那么您需要切换到使用 await 来等待承诺。

async function someFunc() {
    switch(someVal) {
        case '1':
            //Executes first always
            a();    // not asynchronous
            ..
            ..
            ..
            await b();
            //Execute this block only after function b is executed
            ..
            ..
            .. 
            await c()
            //Execute this block only after function c is executed
            ..
            ..
        break;
    }
}

【讨论】:

    猜你喜欢
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2022-01-23
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    相关资源
    最近更新 更多