Typescript 执行承诺直到满足条件(在while循环内)
我想在while循环中封装一个承诺,以便在满足条件之前执行我的方法。我已经尝试实现了这一点,但是我最终得到了无限的承诺,直到堆栈溢出发生 我想在TypeScript中实现如下内容:Typescript 执行承诺直到满足条件(在while循环内),typescript,promise,protractor,Typescript,Promise,Protractor,我想在while循环中封装一个承诺,以便在满足条件之前执行我的方法。我已经尝试实现了这一点,但是我最终得到了无限的承诺,直到堆栈溢出发生 我想在TypeScript中实现如下内容: while (responseSuccess === false) { myClass.executeScript.then((thisWasSuccessful: boolean) => { responseSuccess = thisWasSuccessful; });
while (responseSuccess === false) {
myClass.executeScript.then((thisWasSuccessful: boolean) => {
responseSuccess = thisWasSuccessful;
});
我知道这有点不合常规,但我创建的脚本是应用程序正常执行的对服务器的请求。它并不总是在第一次或n次(不是我可以更改的)返回成功。尝试使用等待运算符
while (responseSuccess === false) {
responseSuccess = await myClass.executeScript;
});
PS:您应该使用TS 2.1或更高版本来针对ES5,我同意其他答案,使用async/await操作符实现这一点非常容易。Typescript的最新稳定版本2.1.4已经可以将异步/等待代码传输到ES5 如果你真的需要只使用标准承诺,也许这样就足够了
this.executeAsync.then(() => {
// after while loop code
});
private executeAsync(): Promise<void> {
return new Promise((callback) => this.executeAsyncLoop(callback));
}
private executeAsyncLoop(callback: () => void): void {
myClass.executeScript.then((thisWasSuccessful: boolean) => {
if(!thisWasSuccessful) executeAsyncLoop(callback);
else callback();
});
}
this.executeAsync.then(()=>{
//while后循环码
});
private executeAsync():承诺{
返回新承诺((回调)=>this.executeAsyncLoop(回调));
}
私有executeAsyncLoop(回调:()=>void):void{
myClass.executeScript.then((thisWasSuccessful:boolean)=>{
如果(!thisWasSuccessful)executeAsyncLoop(回调);
else回调();
});
}
我现在没有测试此代码的环境,因此如果它不起作用,我深表歉意。
while(!wait myClass.executeScript())代码>?如果你在回调中使用然后使用,你需要使用递归方法。当我实现这个时,它被困在myClass.executeScript()上,之后就再也无法执行任何操作了。然后()@fuzzii好吧,很难知道问题出在哪里,因为这是你的脚本代码。如果这部分代码正在执行,而then()中的回调没有被调用,那么脚本没有正确调用promise回调可能有问题。您可以通过调用脚本并确保调用了then()中的回调来隔离它。