evt.waitFor(...)

Method that returns a promise that will resolve when the next matched event is posted.

waitFor is essentially evt.attachOnce(...) but you don’t provide a callback. It accepts the same arguments and return the same promise.

Essentialy the same but not exactly the samearrow-up-right, there is a key difference between a handler attached via waitFor and a handler attached with attach* as explained below.

Without timeout

By default the promise returned by waitFor will never reject.

import { Evt } from "evt";

const evtText = Evt.create<string>();

setTimeout(()=> evtText.post("Hi!"), 1500);

(async ()=>{

    //waitFor return a promise that will resolve next time 
    //post() is invoked on evtText.
    const text = await evtText.waitFor();

    console.log(text);

})();

Run the examplearrow-up-right

With timeout

As with attach*, it is possible to set what is the maximum amount of time we are willing to wait for the event before the promise rejects.

Run the examplearrow-up-right

Difference between evt.waitFor(...) and evt.attachOnce(...)

const pr= evt.waitFor() is NOT equivalent to const pr= evt.attachOnce(()=>{})

evt.waitFor() is designed in a way that makes it safe to use async procedures.

Basically it means that the following example prints A B on the console instead of waiting forever for the secondLetter.

Run this more practical examplearrow-up-right if you want to understand how this behavior prevent from some hard to figure out bugs.

Last updated