Reputation: 6856
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
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...
async
/await
)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