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 prints 13
function yourXFunction(...args) {
const asyncFns = args.slice(0, -1);
const done = args[args.length - 1];
let count = 0;
function closureCallback(val) {
count++;
if (count === asyncFns.length) {
done(val);
}
}
asyncFns.forEach(fn => fn(closureCallback));
}
Promise.all()
asyncX()
возвращали промисы:const yourXFunction = (async1, async2, async3, someCallback) => {
let latest; // последнее значение остаётся
Promise.all([
async1().then(v => {latest = 1; return v;}),
async2().then(v => {latest = 2; return v;}),
async3().then(v => {latest = 3; return v;}),
]).then(results => {
console.log("Last was async" + latest);
someCallback(results[latest - 1]);
});
}
const yourXFunction = (async1, async2, async3, someCallback) => {
let latest; // последнее значение остаётся
Promise.all([
wrap(async1).then(v => {latest = 1; return v;}),
wrap(async2).then(v => {latest = 2; return v;}),
wrap(async3).then(v => {latest = 3; return v;}),
]).then(results => {
someCallback(results[latest - 1]);
});
}
const wrap = (f) => new Promise((res, rej) => f(res));
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);
// через 6 секунд выведет "13"