[英]Use Async functions who call other functions from the same module.exports in Javascript and nodejs
我试图制作一个可以使用 NodeJs 读取 JSON 的应用程序。
我确实得到了好的结果(可能执行起来很慢。)我想要一个可以查看我的代码的专家意见,因为我感到迷茫和困惑......
实际上: killboard.js使用弯曲的 JSON
const bent = require('bent');
const getJSON = bent('json');
const config = require('../config.json');
function showKill(kill)
{
console.log(kill.Killer.Name + " est un meurtrier !");
}
function getKill(killsList) {
return new Promise((resolve, reject) => {
killsList.some(function(kill, index) {
console.log("One kill ...");
showKill(kill);
});
});
}
module.exports = {
exec: async() =>
{
let killsList = await getJSON('https://gameinfo.albiononline.com/api/gameinfo/events?limit=51&offset=0');
await getKill(killsList);
}
}
还有我的APP:
const KillBoar = require('./module/killboard');
KillBoar.exec();
它工作正常....
但是我如何整合:showKill 和 getKill 在“module.exports”中规范。 我的意思是这样的:
module.exports = {
exec: async() =>
{
let killsList = await getJSON('https://gameinfo.albiononline.com/api/gameinfo/events?limit=51&offset=0');
await getKill(killsList);
},
getKill(killsList) {
return new Promise((resolve, reject) => {
killsList.some(function(kill, index) {
console.log("One kill ...");
showKill(kill);
});
});
},
showKill(kill)
{
console.log(kill.Killer.Name + " est un meurtrier !");
}
}
因为如果我这样做,我有这个错误:
(node:7392) UnhandledPromiseRejectionWarning: ReferenceError: getKill is not defined
at Object.exec (C:\Users\Baptiste\Desktop\BotDiscord\KillBoard\module\killboard.js:26:9)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
(node:7392) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which
was not handled with .catch(). (rejection id: 1)
(node:7392) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
谢谢您抽时间回答!
您将它们从 function 定义(称为普通函数)更改为module.exports
object 的方法,因此您现在需要将它们称为方法:
module.exports.getKill(killsList);
…
module.exports.showKill(kill);
或者,您可能会逃脱 this.getKill( this.getKill(…)
/ this.showKill(…)
,有关差异的详细信息,请参见此处。
第三种选择是将它们保留为函数,然后将它们添加到导出中。 然后你可以用任何一种方式调用它们:
function showKill(kill) { … }
module.exports = {
async execc() { … },
showKill,
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.