Edgar
Edgar

Reputation: 6856

How to write the opposite of Promise.race

I have some 3 asynchronous functions.

I have to create function which get that 3 functions and some callback in arguments and call that callback when last asynchronous function has ended, then, send value the of that function's callback argument to callback.

That 3 functions have 1 callback arguments:

const async1 = (cb) => {
    setTimeout(() => {
        cb(1);
    }, 4000);
};
const async2 = (cb) => {
    setTimeout(() => {
        cb(13);
    }, 6000);
};
const async3 = (cb) => {
    setTimeout(() => {
        cb(5);
    }, 3000);
};
const someCallback = (val) => console.log(val);
 yourXFunction(async1, async2, async3, someCallback);
 // for this case, should print 13

Upvotes: 0

Views: 719

Answers (1)

FZs
FZs

Reputation: 18619

You can easily implement a such function:

function yourXFunction(...args){
  const cb=args.pop()
  const cbCreator=i=>value=>{
    if(done.add(i).size===args.length){
      cb(value)
    }
  }
  const done=new Set
  args.map((fn,i)=>{
    fn(cbCreator(i))
  })
}

But note that...

  • Avoid use of callbacks in favor of Promises (or, even better, async/await)
  • Due to single-threadedness of JS, racing 'asynchronous' things may produce unexpected results

Here is a promisified version of your code:

const wait = t => new Promise(rs => setTimeout(rs, t))
const async1 = () => wait(4000).then(()=>1)
const async2 = () => wait(6000).then(()=>13)
const async3 = () => wait(3000).then(()=>5)

function promisifiedYourXFunction(...args){
  return new Promise(resolve=>{
    const cbCreator=i=>value=>{
      if(done.add(i).size===args.length){
        resolve(value)
      }
    }
    const done=new Set
    args.map((fn,i)=>{
      fn().then(cbCreator(i))
    })
  })
}

promisifiedYourXFunction(async1, async2, async3)
.then(console.log)

Upvotes: 1

Related Questions