Skip to content
This repository was archived by the owner on Dec 21, 2021. It is now read-only.

Commit 91ac81b

Browse files
Juuso Takalainentimoxley
authored andcommitted
Don't evaluate the condition twice if it's true from the beginning
also fix comments
1 parent 7cb3912 commit 91ac81b

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/utils/index.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -488,11 +488,14 @@ export async function sleep(ms: number = 0) {
488488
})
489489
}
490490

491+
// condition could as well return any instead of boolean, could be convenient sometimes if waiting until a value is returned. Maybe change if such use case emerges.
491492
/**
492493
* Wait until a condition is true
493494
* @param condition - wait until this callback function returns true
494495
* @param timeOutMs - stop waiting after that many milliseconds, -1 for disable
495496
* @param pollingIntervalMs - check condition between so many milliseconds
497+
* @param failedMsgFn - append the string return value of this getter function to the error message, if given
498+
* @return the (last) truthy value returned by the condition function
496499
*/
497500
export async function until(condition: MaybeAsync<() => boolean>, timeOutMs = 10000, pollingIntervalMs = 100, failedMsgFn?: () => string) {
498501
const err = new Error(`Timeout after ${timeOutMs} milliseconds`)
@@ -502,7 +505,8 @@ export async function until(condition: MaybeAsync<() => boolean>, timeOutMs = 10
502505
}
503506

504507
// Promise wrapped condition function works for normal functions just the same as Promises
505-
while (!await Promise.resolve().then(condition)) { // eslint-disable-line no-await-in-loop
508+
let wasDone = await Promise.resolve().then(condition)
509+
while (!wasDone) {
506510
if (timeout) {
507511
if (failedMsgFn) {
508512
err.message += ` ${failedMsgFn()}`
@@ -511,6 +515,7 @@ export async function until(condition: MaybeAsync<() => boolean>, timeOutMs = 10
511515
}
512516

513517
await sleep(pollingIntervalMs) // eslint-disable-line no-await-in-loop
518+
wasDone = await Promise.resolve().then(condition) // eslint-disable-line no-await-in-loop
514519
}
515-
return condition()
520+
return wasDone
516521
}

0 commit comments

Comments
 (0)