node.js - CommonJS 是同步的,但如果调用异步函数会发生什么

标签 node.js commonjs

CommonJS 使用同步的 require() 语句,但是如果您有这样的模块怎么办:

function asyncFunction() {
    var promise = ...;
    return promise;
}

module.exports = asyncFunction();

这里可能会出现什么样的问题?您是否应该始终为 module.exports 对象返回同步代码?例如,如果 module.exports = {} 它将始终是同步的,但在上述情况下 module.exports 是一个 promise ,假设它不被认为是同步的。如果您需要导入本质上异步的模块,是否有充分的理由在服务器端使用 requireJS?

最佳答案

what kind of problems could arise here?

这违反了 CommonJS 约定,并且会让开发人员感到惊讶。这表明您没有区分代码和数据。服务器上的 Node 中的代码可以而且应该同步加载。数据可以而且应该使用 Promise、回调等。

Is there ever a good reason to use requireJS on the server side

我从来没有见过。就我个人而言,requireJS 很糟糕,如果你的模块引入了它,我绝对没有机会在我的 Node 项目中使用它。

if you need to import a module that is async by nature?

您需要提供具体信息。我从未见过“本质上异步”的 Node 模块,至少不是那些了解代码和数据之间的差异并意识到将远程代码动态加载到正在运行的 Node.js 服务器应用程序中的人是大多数部署都希望看到的出于包括可靠性和安全性在内的充分理由而避免。

关于node.js - CommonJS 是同步的,但如果调用异步函数会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29884893/

相关文章:

javascript - CommonJS递归导入的奇怪之处

typescript :导出保存状态的类实例

javascript - 如何修复导致空对象的循环依赖

design-patterns - javascript模块模式中 undefined variable 的意义是什么

javascript - import 和 const 有什么区别,在 commonjs 中哪个是首选

javascript - 错误: write EPIPE on sendFile()?

javascript - Handlebars 和缓存(模板未更新)

node.js - 让 npm 重新生成 node_modules/.bin 符号链接(symbolic link)

node.js - Dockerized NodeJS在npm运行时选择脚本

node.js - 如何使用 Node.js 创建带缓冲区的读取流