Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 524
anonymous Avatar asked Feb 28 '18 15:02

anonymous


People also ask

How do I use then in node JS?

then is being used for Promises. This only works for Promises and for functions that return Promises. It's not something that is available with all methods that Node has. You don't need to use then when dealing with synchronous functions (and those in your post are).

What is then () in JavaScript?

The then method returns a Promise which allows for method chaining. If the function passed as handler to then returns a Promise , an equivalent Promise will be exposed to the subsequent then in the method chain.

When can I use then ()?

The way to keep the pair straight is to focus on this basic difference: than is used when you're talking about comparisons; then is used when you're talking about something relating to time.

What is the function for then?

Use the then function to access the eventual result of a promise (or, if the operation fails, the reason for that failure). Regardless of the state of the promise, the call to then is non-blocking, that is, it returns immediately; so what it does not do is immediately return the result value of the promise.


1 Answers

.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.

like image 79
Explosion Pills Avatar answered Oct 08 '22 03:10

Explosion Pills