Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript How to Make a Promise?

Andreas Beyer
seal-mask
.a{fill-rule:evenodd;}techdegree
Andreas Beyer
Full Stack JavaScript Techdegree Student 12,474 Points

I just want to chain two functions, why does it not work

function times2(input) {
  setTimeout(function() {
    var number = input*2
    console.log("times2: "+number)
    return number
  },1000)
}

function times4(input) {
  var number = input*4
  console.log("times4: "+number)
  return number
}

function both(input) {
  return new Promise(resolve => {
      console.log(input);
      resolve(input);

  });
}


both(2).then(times2).then(times4)

//it want it to log: 2, 4, 16
//instead it logs: 2, NaN, 4
//WHY?!?!

//i just want to simply chain two functions without changing them, but i do not find any solution to do so in node

1 Answer

Steven Parker
Steven Parker
230,274 Points

For each step in a "then" chain, the result of the previous level is passed to the next. But the "times2" function doesn't return anything. It doesn't help to return something from the "setTimeout" handler, nothing waits for it.

So since "times2" doesn't return anything, "times4" is called with an undefined argument, which results in a calculation returning NaN. Then, 1 second later, the "setTimeout" completes and prints out the "times2" value.

if you make "times2" return a value, you'll see the expected output from "times4" but it will still happen immediately. To have it run in sequence, the "setTimeout" function would need to be converted into a promise, and "times2" would need to return that promise.