如何在打字稿中实现同步功能(Angular)

提摩太

我有一个想要顺序/同步运行的函数,但是我的函数却异步运行。我不知道该如何同步。这是函数的结构:

executeSequentially(paymentDetails){
let paymentStatus: boolean = false;
console.log('action 1');

if(paymentDetails != null){        
  console.log('action 2');

  var x = (window as any).getpaidSetup({           
      callback: async (response) => {  
        console.log('action 3');
          
          if (response != null){   
            console.log('action 4');
            paymentStatus = true;

          }else { 
            console.log('still action 4');
          }
          console.log('action 5');
      }
    }
  );

console.log('action 6');

return paymentStatus;

}

我想在返回“ paymentStatus”之前执行“操作1,操作2,操作3,操作4,操作5和操作6”

但是系统正在执行以下操作:“动作1,动作2,动作6,返回操作,动作3,动作4,动作5

我试图使用异步并等待,但无济于事。谁能帮我吗。感谢在副词

Pascalpuetz

您可以使用async await,但首先必须将异步部分包装到Promise中。看起来像这样:

async function executeSequentially(paymentDetails) {
    let paymentStatus: boolean = false;
    console.log('action 1');

    if(paymentDetails != null) {        
        console.log('action 2');

        // Wrap the part that is asynchronous and await the promise
        await new Promise(resolve => {
            (window as any).getpaidSetup({           
                callback: response => {  
                    console.log('action 3');
                    
                    if (response != null){   
                        console.log('action 4');
                        paymentStatus = true;

                    }else { 
                        console.log('still action 4');
                    }
                    console.log('action 5');
                    resolve(); // resolve the Promise when async execution finished
                }
            });
        });
    }

    console.log('action 6');

    return paymentStatus;
}

并通过一点代码清理,看起来可能像这样:

// extract promisification into its own function (no need for async, you return a promise anyway)
function promisifiedGetPaidSetup():Promise<boolean> {
    return new Promise(resolve =>
        (window as any).getpaidSetup({           
            // resolve with a boolean value, cleaner design since you don't set a variable outside
            callback: response => resolve(response != null) 
        })
    );
}

async function executeSequentially(paymentDetails):Promise<boolean> {
    // Either return the result from the promise, or false if payment details are not present
    return paymentDetails ? await promisifiedGetPaidSetup() : false;
}

这里是带有第二个示例“正在运行”Playground的链接重要的是要注意您的代码仍将是异步的(这就是为什么它现在返回一个promise的原因,它本质上是异步的)。但是里面的语句将按顺序执行。因此,无论您在何处使用该executeSequentially函数,如果要伪同步运行它,都必须等待它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章