#I want to resolve a promise when a list's length is 0. What is the right tool for the job?

20 messages · Page 1 of 1 (latest)

umbral panther
#

I want to resolve a promise when a list's length is 0. What is the right tool for the job? I think I need to pass two Promises into Promise.race :

  1. A promise that immediately resolves if list.length === 0
  2. A promise that polls the list.length, and when it's 0, it resolves.

I don't like the design of this because it involves polling. Can someone recommend a better implementation or library I should use for this?

crimson aspen
#

@umbral panther Depends a lot on the context of what you're trying to do, I think.

#

If this is some sort of UI, the UI framework being used would generally dictate how you're handling it - they generally have some sort of tool for these sort of reactive events.

#

Generically you could look at something like RxJS - though it's a very complex hammer for what might be a fairly small nail - or else some sort of signal implementation: https://github.com/tc39/proposal-signals

umbral panther
#

@crimson aspen Yeah this is UI. The list is actually a "list" of timers. I'm trying to wait until all the timers are done before I move on to the next step

#

I tried to hand wave the timer detail because I thought it would make the question much more confusing: I already have to build something around them to keep track of when they are created and when they are finished.

merry marlin
#

Can the timers be promises that you await?

#

or is there an event they trigger that can be used to schedule a check?

umbral panther
#

I can do either

#

Right now they are stored in a list like this and they fire jquery events when created and completed:

export type TimeoutData = {
  cancelTimeout: ClearTimeoutFunction;
  timeoutIdentifier: TimeoutID;
  context: string;
};

const timers = new Map<TimeoutData, LastTimeoutEvent>(); // I'll probably convert this to a TimeoutData[] in an hour or two
umbral panther
#

The place that wants to check if they are running currently has no association with this list of timers; I could export timers to give it this access, I just haven't needed to yet. I've been using the events instead

#

Maybe you're thinking I could do Promise.all(timers). I like that idea. I'll pursue that, but let me know if that's not what you intended

merry marlin
#

Is the list of timers static, or could more be added?

crimson aspen
umbral panther
umbral panther
# merry marlin something like this

It's kinda difficult for me to reason about potential race conditions. Is there any possibility that list could be modified while a promise is traversing it? I don't know what effect that would have

merry marlin
#

The list won't be modified while promise.all activates

#

But if you add to the list after promise.all() then the new promises won't be awaited