Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript How to Make a Promise?

Andreas Beyer
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

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

function both(input) {
  return new Promise(resolve => {



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

//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
221,292 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.