简体   繁体   中英

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.

I have a function that needs to run when another returns true or after waiting half a second.

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.

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.

With some recursion (recurse with timeout until its 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):

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

okToProceed must return a Promise like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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