这实际上与异步函数没有任何关系.如果你想在内部调用一个函数and,导出它,定义它first,然后导出它.
async function doStuff() {
// ...
}
// doStuff is defined inside the module so we can call it wherever we want
// Export it to make it available outside
module.exports.doStuff = doStuff;
解释您try 的问题:
module.exports.PrintNearestStore = async function PrintNearestStore(session, lat, lon) {
...
}
这不会在模块中定义函数.函数定义是一个函数expression.函数表达式的名称仅在函数本身内部创建变量.更简单的例子:
var foo = function bar() {
console.log(typeof bar); // 'function' - works
};
foo();
console.log(typeof foo); // 'function' - works
console.log(typeof bar); // 'undefined' - there is no such variable `bar`
另见第Named function expressions demystified页.如果你在任何地方都提到module.exports.PrintNearestStore
,你当然可以提到这个函数.
module.exports.PrintNearestStore = PrintNearestStore;
var PrintNearestStore = async function(session, lat, lon) {
}
好的.问题是,当您将PrintNearestStore
指定给module.exports.PrintNearestStore
时,它的值是undefined
.执行顺序如下:
var PrintNearestStore; // `undefined` by default
// still `undefined`, hence `module.exports.PrintNearestStore` is `undefined`
module.exports.PrintNearestStore = PrintNearestStore;
PrintNearestStore = async function(session, lat, lon) {}
// now has a function as value, but it's too late
更简单的例子:
var foo = bar;
console.log(foo, bar); // logs `undefined`, `undefined` because `bar` is `undefined`
var bar = 21;
console.log(foo, bar); // logs `undefined`, `21`
如果您更改了顺序,它将按预期工作.
module.exports.PrintNearestStore = async function(session, lat, lon) {
await PrintNearestStore(session, lat, lon);
}
var PrintNearestStore = async function(session, lat, lon) {
...
}
这是因为分配给module.exports.PrintNearestStore
is executedPrintNearestStore
的函数将函数作为其值.
更简单的例子:
var foo = function() {
console.log(bar);
};
foo(); // logs `undefined`
var bar = 21;
foo(); // logs `21`