'Correct async function export in node.js
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
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
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 async function both: inside and outside (exports) module?
Solution 1:[1]
Error with first case: PrintNearestStore - Function expression, so this name not available outside.
error with second case: using variable, instead Function declaration. In this case, declaration of variable PrintNearestStore are hoisted, so, you can use this name before line var PrintNearestStore = ..., but in this case value would be undefined.
So, simplest solution change second variant like this:
module.exports.PrintNearestStore = PrintNearestStore;
async function PrintNearestStore(session, lat, lon) {
}
Solution 2:[2]
an alternative would be to export like this. // foo.js
export async function foo(){
console.log('I am greatest of all.'); // for the person who reads it, just say it.
}
then use it in other scripts like
import { foo } from './foo'
foo();
Solution 3:[3]
export let handlePostStore = async (data) => {
console.log('post');
return data;
};
// to import
import { handlePostStore } from 'your_path_here';
// to call it
handlePostStore(data)
Solution 4:[4]
Some examples:
module.exports.func1 = async function func1(id) { // name is preferred by linter
//
};
module.exports.func1 = async function (id) { // ok
//
};
module.exports.func1 = async (id) => { // simpler
//
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Grundy |
| Solution 2 | rajesh_chaurasiya |
| Solution 3 | Julio fils |
| Solution 4 |
