我有我有下面的代码自定义模块:正确的异步函数引出
module.exports.PrintNearestStore = async function PrintNearestStore(session, lat, lon) {
...
}
它工作得很好,如果叫我的模块之外的功能,但是,如果我叫我里面运行时遇到错误:
(node:24372) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: PrintNearestStore is not defined
当我改变语法:
module.exports.PrintNearestStore = PrintNearestStore;
var PrintNearestStore = async function(session, lat, lon) {
}
它开始做工精细的内部模块,但没有欧tside模块 - 我有错误:
(node:32422) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: mymodule.PrintNearestStore is not a function
所以我改变了代码:
module.exports.PrintNearestStore = async function(session, lat, lon) {
await PrintNearestStore(session, lat, lon);
}
var PrintNearestStore = async function(session, lat, lon) {
...
}
而现在它在所有情况下工作:内部和外部。但是想要理解语义,并且如果有更美好更短的方式来编写它呢?如何正确定义和使用异步函数:内部和外部(出口)模块?
谢谢你,我明白了。刚刚重新排序的函数定义(现在删除'var')和'module.exports' - 函数定义首先。我发现对于内部调用函数定义顺序并不重要:我在定义之前调用了函数,但是对于'module.exports'它很重要。 –
@AlekseyKontsevich:FWIW,在源代码中*行B之前的行A *并不意味着行A *在*行B之前执行* *。最后,执行顺序是唯一重要的事情。当然,函数定义必须在函数调用之前进行评估。但是,由于吊装,JS的执行顺序可能不明显。 –