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

时间:2020-09-26 08:06:21

标签: angular typescript function synchronous sequential

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

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,acton 5

我尝试使用异步和等待,但无济于事。 谁能帮我吗。感谢adv

2 个答案:

答案 0 :(得分:1)

您可以使用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的链接,其中包含第二个示例“ in action”。重要的是要注意您的代码仍将是异步的(这就是为什么它现在返回一个promise的原因,它本质上是异步的)。但是里面的语句将按顺序执行。因此,无论您在哪里使用executeSequentially函数,如果要伪同步地运行它,都必须等待它。

答案 1 :(得分:-1)

有多种解决方案,但更简单的解决方案是创建一个promises数组并使用Promise.All等待所有数组promise被解决。因此,代码应如下所示。

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

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

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

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

promises.push(console.log('action 6'));

await Promise.all(promises)

return paymentStatus;

}