Resolve a promise if a condition is met, otherwise keep it pending?

Hi everybody!

I’m trying to put pending promise on hold when a user clicks on button or change tab, etc. Basically, Is it possible to make sure that pending promises are only resolved when a certain condition is met? And keep it pending until the condition changes? I tried to chain promises like these but it doesn’t seem to work:

Thanks a lot!

I’m not 100% sure what you’re trying to do, but you’ll likely need to build your own Promise with the constructor.

Here’s one that wraps a classic callback style function:

function ajaxPromise(request) {
  return new Promise((resolve, reject) => {
    ajaxCallback(request, (error, data) => {
      if (error) {
        return reject(error);
      }
      return resolve(data);
    }
  });
}

Here’s one that just resolves after a specified timeout:

function wait(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms);
  }
}

Let me know if you need any more explanation about how to use that.

1 Like

Thanks! But I don’t think my problem relates to these examples. What I am trying to do is to just resolve/reject the promise when the condition isHidden is met. Otherwise, I want to keep it pending as long as isHidden is false. So I think it’s definitely not an if… else between reject and resolve, but between pending and reject/resolve.

Can you go through step-by-step what the interaction is?

  1. User clicks a button: fetch is called
  2. User leaves page: isHidden set
  3. fetch completes but resolution pending on isHidden being unset
  4. User comes back: isHidden unset: fetch resolves

Something like this? And if so, why?