如何在 typescript 中实现同步函数 (Angular)

How to implement synchronous functions in typescript (Angular)

我有一个函数想要 运行 sequentially/synchronously,但我的函数是 运行 异步的。我不知道如何使它同步。这是函数的结构。

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

我想在 returning“paymentStatus”之前执行“操作 1、操作 2、操作 3、操作 4、操作 5 和操作 6”,但系统正在执行:“操作 1,操作 2,操作 6,return 操作,操作 3,操作 4,操作 5”。我尝试使用异步和等待,但无济于事。

有多种解决方案,但更简单的方法是创建一个承诺数组并使用 Promise.all 等待所有数组承诺都得到解决。所以代码应该如下所示。

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;

}

您可以使用 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;
}

这里是 link 到 Playground 第二个例子“在行动”。重要的是要注意你的代码仍然是异步的(这就是为什么它 returns 现在是一个 promise,它本质上是异步的)。但是里面的语句会按顺序执行。所以无论你在哪里使用 executeSequentially 函数,如果你想 运行 就必须等待它 pseudo-synchronously.