簡體   English   中英

在 Javascript 和 nodejs 中使用從同一 module.exports 調用其他函數的異步函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM