EVT
Search…
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 same, 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.
1
import { Evt } from "evt";
2
3
const evtText = new Evt<string>();
4
5
setTimeout(()=> evtText.post("Hi!"), 1500);
6
7
(async ()=>{
8
9
//waitFor return a promise that will resolve next time
10
//post() is invoked on evtText.
11
const text = await evtText.waitFor();
12
13
console.log(text);
14
15
})();
Copied!

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.
1
import { Evt, EvtError } from "evt";
2
3
const evtText = new Evt<string>();
4
5
(async ()=>{
6
7
try{
8
9
const text = await evtText.waitFor(500);
10
11
console.log(text);
12
13
}catch(error){
14
15
console.assert(error instanceof EvtError.Timeout);
16
//Error can be of two type:
17
// -EvtError.Timeout if the timeout delay was reached.
18
// -EvtError.Detached if the handler was detached before
19
// the promise returned by waitFor have resolved.
20
21
console.log("TIMEOUT!");
22
23
}
24
25
})();
26
27
//A random integer between 0 and 1000
28
const timeout= ~~(Math.random() * 1000);
29
30
//There is a fifty-fifty chance "Hi!" is printed else it will be "TIMEOUT!".
31
setTimeout(
32
()=> evtText.post("Hi!"),
33
timeout
34
);
Copied!

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.
1
import { Evt } from "evt";
2
3
const evtText = new Evt<string>();
4
5
(async ()=>{
6
7
const firstLetter = await evtText.waitFor();
8
const secondLetter = await evtText.waitFor();
9
10
console.log(`${firstLetter} ${secondLetter}`);
11
12
})();
13
14
evtText.post("A");
15
evtText.post("B");
16
17
//"A B" is printed to the console.
Copied!
Run this more practical example if you want to understand how this behavior prevent from some hard to figure out bugs.
Last modified 1yr ago