user10207707
user10207707

Reputation:

Use nested callbacks

Currently I try to figure out how nested callbacks do work in Javascript. But on my example the console does not print anything. The example is pretty basic- should print letters: abc.

Code

function getA() {
  return setTimeout(() => 'a', 1000);
}

function getB() {
  return setTimeout(() => 'b', 2000);
}

function getC() {
  return setTimeout(() => 'c', 3000);
}

function handleWithCallback(callback1, callback2, callback3) {
  callback1(a =>
    callback2(b =>
      callback3(c => console.log(a + b + c))
    )
  );
}

handleWithCallback(getA, getB, getC);

Upvotes: 0

Views: 43

Answers (1)

trincot
trincot

Reputation: 351384

In handleWithCallback you call the callback functions by passing arguments, but notice how your actual getX callback functions don't use that argument. They should take a callback function as argument and call it.

NB: I reduced the timeout delays so you don't have to wait that long to see the result :)

function getA(cb) {
  return setTimeout(() => cb('a'), 100);
}

function getB(cb) {
  return setTimeout(() => cb('b'), 200);
}

function getC(cb) {
  return setTimeout(() => cb('c'), 300);
}

function handleWithCallback(callback1, callback2, callback3) {
  callback1(a =>
    callback2(b =>
      callback3(c => console.log(a + b + c))
    )
  );
}

handleWithCallback(getA, getB, getC);

Upvotes: 3

Related Questions