Home > front end >  How to promise.race an array of async callbacks vs a timeout
How to promise.race an array of async callbacks vs a timeout

Time:11-12

I have a set of callbacks that may run on different durations before I close my web app. I also have a timeout where if it reaches past the timeout duration, I also close the application. The reason for this is to prevent the callbacks from blocking in closing the web app if it passes timeout duration.

Here is my current solution:

const closeCallbacks = [
  // for sample purposes. i assigned timeouts to mock that it takes longer to run these callbacks then my timeout duration. In the real world scenario, these are not timeouts but ordinary functions that I want to run but may take time to run
  (async) => setTimeout(() => console.log('cb1'), 3000),
  (async) => setTimeout(() => console.log('cb2'), 5000)
];
// For some context `cb: () => Promise<void>`
const callbacks = closeCallbacks.map((cb) => cb());
const timeout = new Promise((res) => setTimeout(() => console.log('timeout'), 4000));

Promise.race([Promise.all(callbacks), timeout]).then((data) => {
  // Instantly returns Promise.all(callbacks) even if timeout is still in the process of doing there thing
  console.log(data)

  executeClose();
});

My current solution is returning Promise.all(callbacks) even if it hasn't called expected callbacks to run yet. What I expect to happen is that it passes through my timeout instead since it has a timer of 4000 and the last closeCallback has a timer of 5000.

What am I doing wrong?

CodePudding user response:

Your closeCallbacks are not async, You need them to return a promise.

const closeCallbacks = [
  // for sample purposes. i assigned timeouts to mock that it takes longer to run these callbacks then my timeout duration
  async () => new Promise(resolve => setTimeout(() => resolve(console.log('cb1')), 3000)),
  async () => new Promise(resolve => setTimeout(() => resolve(console.log('cb2')), 5000)),
];

CodePudding user response:

This creates a parameter named async not an async function

(async) => {}

Your timeout function never calls res parameter

const wait = (cb, time) => new Promise(r => { cb(); r() }, time)

const closeCallbacks = [
  () => wait(() => console.log('cb1'), 3000),
  () => wait(() => console.log('cb2'), 5000)
];

const timeout = new Promise((res) => setTimeout(() => console.log('timeout'); res(), 4000));
  • Related