Srinivas Nahak
Srinivas Nahak

Reputation: 1876

How to use .then() in node.js?

I'm a complete beginner in node.js. I've just read we can use .then() function for executing several functions in particular order. I was going to write the code this way:

function one(){
  console.log("one")
}
function two(){
  console.log("two")
}
function three(){
  console.log("three")
}
one().then(two()).then(three())

But I'm getting this error:

TypeError: Cannot read property 'then' of undefined
at Object.<anonymous> (C:\chat\test.js:10:6)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:502:3

Upvotes: 23

Views: 82310

Answers (5)

Alexander Kahoun
Alexander Kahoun

Reputation: 2488

.then() is for Promises. You also want to pass the function, not its return type as the .then() parameter. To make your example work, try:

function one(){
  return Promise.resolve(console.log("one"));
}
function two(){
  return Promise.resolve(console.log("two"));
}
function three(){
  return Promise.resolve(console.log("three"));
}

one()
  .then(two)
  .then(three)
  .catch(error => { 
    console.error('uhoh');
  });

Also, while this may work for your example. You won't normally use Promise.resolve(). You'll find it more typical to see the constructor used:

function func(a, b) {
  return new Promise((resolve, reject) => {
    if (!a || !b) return reject('missing required arguments');
    return resolve(a + b);
  }
}

Calling reject on an error condition, and resolve on success. Rejections are routed to the first .catch(). I encourage you to read up on Promises in the link above.

Upvotes: -1

nanobar
nanobar

Reputation: 66355

.then only works if the function returns a Promise. Promises are used for asynchronous tasks, so you can wait on something before doing something else.

function one(){
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('one')
      resolve();
     }, 1000);
  });
}

function two(){
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('two')
      resolve();
     }, 1000);
  });
}

function three(){
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('three')
      resolve();
     }, 1000);
  });
}

one().then(two).then(three);

You can use the resolve (and second argument reject) to return a result to the next .then or .catch:

function one(){
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('one');
     }, 1000);
  });
}

function two(){
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('two');
     }, 1000);
  });
}

function three(){
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error('three'));
     }, 1000);
  });
}

one()
  .then((msg) => {
    console.log('first msg:', msg);
    return two();
  })
  .then((msg) => {
    console.log('second msg:', msg);
    return three();
  })
  .then((msg) => {
    // This one is never called because three() rejects with an error and is caught below.
    console.log('third msg:', msg);
  })
  .catch((error) => {
    console.error('Something bad happened:', error.toString());
  });

Upvotes: 6

Explosion Pills
Explosion Pills

Reputation: 191749

.then is a method that exists on Promises and is a mechanism for code synchronization. Your code is not asynchronous, so you wouldn't need to use promises. You can just call

one();
two();
three();

If your code does something asynchronous, then you can use promises and .then. Asynchronous operations are things like reading/writing files, http requests, timers, and many more.

Just as an example, we can use the built in Promise to create our own asynchronous operations:

I don't recommend you do this normally. We're just using it as an example. In most cases you can call functions that already return promises for you.

function one() {
  return new Promise(resolve => {
    console.log("one");
    resolve();
  });
}

function two() {
  return new Promise(resolve => {
    console.log("two");
    resolve();
  });
}

function three(){
   console.log("three")
}

one().then(() => two()).then(() => three());

Also note that when you use .then, you need to pass a callback. two() calls the two function immediately, so it's not the same as () => two().


Next, you can often use async/await instead of .then which I think makes your code easier to reason about in most cases.

async function run() {
  await one();
  await two();
  three();
}
run();

This is the same as the second example rewritten to use await instead of .then. You can think of everything after await as being inside of a .then chained to the expression after await.


Finally, you should handle errors by either chaining .catch to the promises or using the normal try/catch inside of async functions.

Upvotes: 41

melvinv
melvinv

Reputation: 144

Then is usually used in the context of Promises. You could start reading more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

Upvotes: 1

federico scamuzzi
federico scamuzzi

Reputation: 3778

the .then() function is used for the PROMISE (so for async function ) when you need to KNOW WHEN IT'S FINISHED (and it is finished ok .. or KO ) ..so you have

MYASYNCFUNCTION().then(function(response({

 //do what you want when it's finish and everything ok .. with the result

}).catch(function(error){
 // it's finshed but with error
})

IN your example .. you don't have .then() function cause they're simple function .. but if you want to have it (i don't know why . they've not async stuff inside .. but you can)

so

// install it via npm install promise

var Promise = require('promise');

function one(){
var promise = new Promise(function (resolve, reject) {
  resolve('one');
  });
});

}

and then

one().then(function(resp){ console.log(resp) })

Hope it helps you!!

Upvotes: 0

Related Questions