简体   繁体   English

如何等到函数为真或角度2经过一段时间

[英]How to wait until a function is true or some time has passed in angular 2

Complete beginner at angular 2 and currently rather baffled by it all. 在角度2完全适合初学者,目前对此颇为困惑。

I have a function that needs to run when another returns true or after waiting half a second. 我有一个需要在另一个返回true或等待半秒后运行的函数。

private myFunction(details: Stuff) {
    if (this.okToProceed(details))
    {
        this.doStuff(details);
    }
}

If it's not ok to proceed I want to try again in 100 ms but if I've waited 500ms then I want to doStuff anyway. 如果不能继续进行,我想在100毫秒内重试,但是如果我已经等待了500毫秒,那么无论如何我都想做东西。

I've been messing around with setTimeout and setInterval and trying to make an observable of the okToProceed function but I'm not getting anywhere. 我一直在弄乱setTimeout和setInterval,并试图使okToProceed函数成为可观察到的东西,但是我什么都没得到。

With some recursion (recurse with timeout until its okToProceed): 进行一些递归(在超时之前递归直到okToProceed):

private myFunction(details: Stuff, i=0) {
    if (i>=5 || this.okToProceed(details)) {
        return this.doStuff(details);
    }
    setTimeout(this.myFunction.bind(this),100,i+1);
}

Or using some fancy ES7 doing real cool async stuff (no need to check recursively): 或使用一些花哨的ES7做真正酷的异步工作(无需递归检查):

private async myFunction(details: Stuff) {
    if (await this.okToProceed(details)) {
        return this.doStuff(details);
    }
}

okToProceed must return a Promise like this: okToProceed必须返回这样的Promise:

okToProceed(details){
    return Promise.resolve(true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM