0

I have a function like this below,

class MyClass {

    myFunction() {
      return new Promise((resolve, reject) => {
        if(....) {
          resolve(data)
           } else {
          reject(err)
         }
      }) 
    }
}

module.exports = MyClass;

I can reach this class from another files like this below

const MyClass = require('./fileName.js').prototype;

const exportData = MyClass.myFunction().then(data => {
    return data;
}).catch(err => {
    console.log(err)
})

console.log(exportData) //exportData is not null

module.exports = exportData;

when I want to export this exportData to other files, value of exportData is null in other files. But if I do not export this exportData, it is not null. How can solve this problem ? Thanks.

SefaUn
  • 824
  • 1
  • 7
  • 23
  • 1
    Try moving the module.exports within the then block. promise makes a block synchronous but they themselves are async blocks. But use care if reject block is called in which case exportData could be null. – Karan Gaur May 28 '21 at 09:01
  • 1
    Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – MrCodingB May 28 '21 at 10:29
  • @KaranGaur can you give an example ? – SefaUn May 28 '21 at 11:51
  • @MrCodingB I think that is my problem. can you give code example ? – SefaUn May 28 '21 at 11:52

1 Answers1

3

This link should give you further insight.

Try exporting the promise itself. That would be the best practice rather than sending the data. This way you can maximize the async properties of JS by only performing it once required. The promise will be executed only once and you can fetch the data repeatedly without exerting a proccessing load.

const MyClass = require('./fileName.js').prototype;

const exportData = MyClass.myFunction()
// Here you are exporting the promise as is.
module.exports = exportData;

As mentioned in the link. The downside would be that the data won't be refreshed. So once a reject is called, each time it would be a reject, the same goes for the data, making it static.

Karan Gaur
  • 809
  • 7
  • 20
  • I understood what you tell me. this technique can not clearly solve my problem. but it is helpful. thanks – SefaUn May 29 '21 at 19:37