Promise based sequence converting into Callback based

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

Answers:

Answer
[f1, f2, f3, f4].reduce((promise, f) => promise.then(f), Promise.resolve(10))

in your runPromiseInSequence basically boils down to

Promise.resolve(10).then(f1).then(f2).then(f3).then(f4);

This pattern doesn't work with callbacks, as there is no value to start with that we could chain on. Instead, we need to nest:

f1(10, r1 => f2(r1, r2 => f3(r2, r3 => f4(r3, r4 => cb(r4))));

This can be achieved using reduceRight:

[f1, f2, f3, f4].reduceRight((cb, f) => r => f(r, cb), cb)(10)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.