【问题标题】:Export Return Value To Other Files in Node.js [duplicate]将返回值导出到 Node.js 中的其他文件 [重复]
【发布时间】:2021-08-16 11:57:20
【问题描述】:

我有一个像下面这样的函数,

class MyClass {

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

module.exports = MyClass;

我可以从下面这样的另一个文件访问这个类

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;

当我想将此exportData 导出到其他文件时,exportData 的值在其他文件中为空。但是如果我不导出这个exportData,它就不是空的。 如何解决这个问题? 谢谢。

【问题讨论】:

  • 尝试在 then 块中移动 module.exports。 promise 使块同步,但它们本身是异步块。但是如果调用了拒绝块,请小心,在这种情况下 exportData 可能为空。
  • @KaranGaur 你能举个例子吗?
  • @MrCodingB 我认为这是我的问题。你能给出代码示例吗?

标签: javascript node.js


【解决方案1】:

这个link 应该会给你更多的见解。

尝试导出承诺本身。这将是最好的做法,而不是发送数据。这样,您可以通过仅在需要时执行 JS 来最大化 JS 的异步属性。 Promise 只会执行一次,您可以重复获取数据而不会施加处理负载。

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

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

如链接中所述。缺点是数据不会被刷新。因此,一旦调用了拒绝,每次都是拒绝,数据也是如此,使其成为静态的。

【讨论】:

  • 我明白你告诉我的。这种技术不能清楚地解决我的问题。但这很有帮助。谢谢
猜你喜欢
  • 2021-09-30
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2021-08-16
  • 2017-07-07
  • 2022-08-12
  • 1970-01-01
相关资源
最近更新 更多