Javascript 更正 node.js 中的异步函数导出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46715484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct async function export in node.js
提问by Aleksey Kontsevich
I had my custom module with following code:
我的自定义模块带有以下代码:
module.exports.PrintNearestStore = async function PrintNearestStore(session, lat, lon) {
...
}
It worked fine if call the function outside my module, however if I called inside I got error while running:
如果在我的模块外调用该函数它工作正常,但是如果我在内部调用我在运行时出错:
(node:24372) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: PrintNearestStore is not defined
(节点:24372)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):ReferenceError:未定义PrintNearestStore
When I changed syntax to:
当我将语法更改为:
module.exports.PrintNearestStore = PrintNearestStore;
var PrintNearestStore = async function(session, lat, lon) {
}
It started to work fine inside module, but fails outside the module - I got error:
它开始在模块内部正常工作,但在模块外部失败 - 我收到错误:
(node:32422) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: mymodule.PrintNearestStore is not a function
(node:32422) UnhandledPromiseRejectionWarning: Unhandled promise Rejection (rejection id: 1): TypeError: mymodule.PrintNearestStore is not a function
So I've changed code to:
所以我已经将代码更改为:
module.exports.PrintNearestStore = async function(session, lat, lon) {
await PrintNearestStore(session, lat, lon);
}
var PrintNearestStore = async function(session, lat, lon) {
...
}
And now it works in all cases: inside and outside. However want to understand semantics and if there is more beautiful and shorter way to write it? How to correctly define and use asyncfunction both: inside and outside (exports) module?
现在它适用于所有情况:内部和外部。但是想了解语义,是否有更漂亮更短的写法呢?如何正确定义和使用异步函数:内部和外部(导出)模块?
回答by Felix Kling
This doesn't really have anything to with async functions specially. If you want to call a function internally andexport it, define it firstand then export it.
这实际上与异步函数没有任何关系。如果要在内部调用函数并导出它,请先定义它,然后再导出它。
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;
Explanation of the problems with your attempts:
您尝试的问题的解释:
module.exports.PrintNearestStore = async function PrintNearestStore(session, lat, lon) {
...
}
This does not define a function in the module. The function definition is a function expression. The name of a function expression only creates a variable inside the function itself. Simpler example:
这不会在模块中定义函数。函数定义是一个函数表达式。函数表达式的名称仅在函数本身内部创建一个变量。更简单的例子:
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`
See also Named function expressions demystified. You could of course refer to the function if you'd refer to module.exports.PrintNearestStoreeverywhere.
另见命名函数表达式揭秘。如果您要引用module.exports.PrintNearestStore任何地方,您当然可以引用该函数。
module.exports.PrintNearestStore = PrintNearestStore;
var PrintNearestStore = async function(session, lat, lon) {
}
This is almostOK. The problem is that the value of PrintNearestStoreis undefinedwhen you assign it to module.exports.PrintNearestStore. The order of execution is:
这几乎没问题。问题是 的值PrintNearestStore是undefined当您将其分配给 时module.exports.PrintNearestStore。执行顺序为:
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
Simpler example:
更简单的例子:
var foo = bar;
console.log(foo, bar); // logs `undefined`, `undefined` because `bar` is `undefined`
var bar = 21;
console.log(foo, bar); // logs `undefined`, `21`
If you changed the order it would work as expected.
如果您更改了顺序,它将按预期工作。
module.exports.PrintNearestStore = async function(session, lat, lon) {
await PrintNearestStore(session, lat, lon);
}
var PrintNearestStore = async function(session, lat, lon) {
...
}
This works because by the timethe function assigned to module.exports.PrintNearestStoreis executed, PrintNearestStorehas the function as its value.
这工作,因为在时间分配给功能module.exports.PrintNearestStore被执行,PrintNearestStore所具有的功能作为其值。
Simpler example:
更简单的例子:
var foo = function() {
console.log(bar);
};
foo(); // logs `undefined`
var bar = 21;
foo(); // logs `21`
回答by Grundy
Error with first case: PrintNearestStore- Function expression, so this name not available outside.
第一种情况出错:PrintNearestStore- 函数表达式,因此此名称在外部不可用。
error with second case: using variable, instead Function declaration. In this case, declaration of variable PrintNearestStore are hoisted, so, you can use this name beforeline var PrintNearestStore = ..., but in this case value would be undefined.
第二种情况的错误:使用变量,而不是函数声明。在这种情况下,变量 PrintNearestStore 的声明被提升,因此,您可以在line之前使用此名称var PrintNearestStore = ...,但在这种情况下, value 将为undefined。
So, simplest solution change second variant like this:
因此,最简单的解决方案更改第二个变体,如下所示:
module.exports.PrintNearestStore = PrintNearestStore;
async function PrintNearestStore(session, lat, lon) {
}

