You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Very often when writing integration tests I need to wait for a condition to be true to continue (for example the database record is there, or an SMS message has arrived). I use the function below repeatedly and I would love if it can be part of @std/async. If you see value in it, would contribute as PR. Please let know.
/** * Wait for a condition to be true, jumping every `jump` milliseconds until * `timeout` is reached. Can be used as: * * ```typescript * let i = 0; * const id = setInterval(() => i++, 42); * await waitFor(() => i > 10); * clearInterval(id); * assert(i > 10); * ``` * * @param condition - predicate returning a (potentially promised) boolean * @param timeout - maximum wait time (default 20s, 0 for infinite) * @param jump - the time to wait between checks (default 100ms) */functionwaitFor(condition: ()=>boolean|Promise<boolean>,timeout=20000,jump=100){// Time we start the checks so that we canconststart=Date.now();returnnewPromise(function(resolve,reject){// If condition is "truthy" resolve, if timeout reject, otherwise keep waitingconstcheck=asyncfunction(): Promise<void>{constvalue=awaitcondition();if(value)returnresolve(value);consttime=Date.now()-start;if(time>timeout)returnreject(newError("Timeout ("+timeout+"ms) waiting for condition!"));setTimeout(check,jump);};// Start checkingsetTimeout(check);});}
The text was updated successfully, but these errors were encountered:
Very often when writing integration tests I need to wait for a condition to be true to continue (for example the database record is there, or an SMS message has arrived). I use the function below repeatedly and I would love if it can be part of
@std/async
. If you see value in it, would contribute as PR. Please let know.The text was updated successfully, but these errors were encountered: