I am trying to convert Promise based runPromiseInSequence into callback based function. Here is what I have so far. I do not quite understand how callbacks work that is why I am doing this exercise. Let me know what I am doing wrong and how I can fix it.
Callback based
function runPromiseInSequence(fns, cb) {
return fns.reduce(
(promiseChain, currentFunction) => promiseChain(currentFunction),
cb()
);
}
function stepOne(err, a = 'stepOne') {
if (err) {
console.log(err);
} else {
console.log(`stepOne: ${a}`);
a * 5;
}
}
function stepTwo(err, a) {
if (err) {
console.log(err);
} else {
console.log(`stepTwo: ${a}`);
a * 2;
}
}
function stepThree(err, a) {
if (err) {
console.log(err);
} else {
console.log(`stepThree: ${a}`);
a * 3;
}
}
function stepFour(err, a) {
if (err) {
console.log(err);
} else {
console.log(`stepFour: ${a}`);
a * 4;
}
}
const promiseArr = [stepOne, stepTwo, stepThree, stepFour];
console.log(series(promiseArr, 10)); // error cb is not a function
Promise based
function runPromiseInSequence(arr, input) {
return arr.reduce(
(promiseChain, currentFunction) => promiseChain.then(currentFunction),
Promise.resolve(input)
);
}
// promise function 1
function p1(a) {
return new Promise((resolve, reject) => {
resolve(a * 5);
});
}
// promise function 2
function p2(a) {
return new Promise((resolve, reject) => {
resolve(a * 2);
});
}
// function 3 - will be wrapped in a resolved promise by .then()
function f3(a) {
return a * 3;
}
// promise function 4
function p4(a) {
return new Promise((resolve, reject) => {
resolve(a * 4);
});
}
const promiseArr = [p1, p2, f3, p4];
runPromiseInSequence(promiseArr, 10)
.then(console.log); // 1200
I am trying to understand how callbacks work but I am getting it wrongGetting it wrong how? Are you getting errors? If so, what errors?// error cb is not a functionis this the error?runPromiseInSequence(promiseArr, 10), so the error is correct, it's not a function