Open In App

How to export promises from one module to another module node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript is an asynchronous single-threaded programming language. Asynchronous means multiple processes are handled at the same time. Callback functions vary for the asynchronous nature of the JavaScript language. A callback is a function that is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime, but the main problem with the callback function is the callback hell problem. The solution of callback hell is using the promises in this article we will discuss how to export from one module to another module. 

Project Structure: It will look like this.

FirstModule.js




function check(number) {
  return new Promise((Resolve, reject) => {
    if (number % 2 == 0) {
      Resolve("The number is even")
    }
    else {
      reject("The number is odd")
    }
  })
}
  
// Exporting check function
module.exports = {
  check: check
};


SecondModule.js




// Importing check function
const promise = require("./FirstModule.js")
  
// Promise handling
promise.check(8).then((msg) => {
  console.log(msg)
}).catch((msg) => {
  console.log(msg)
})


Run SecondModule.js file using the below command:

node SecondModule.js

Output:

The number is even

Last Updated : 26 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads