Node.js模块函数的访问参数

Access parameter of Node.js module function

本文关键字:访问 参数 函数 js 模块 Node      更新时间:2023-09-26

我对node.js完全陌生,我找不到类似的问题。我相信这对你们中的一个来说很容易解决……至少我是这么想的。

我正在尝试使用npm mediawiki模块为node.js获得一个特殊的段落!我使用预定义的函数获得段落,如下所示:

bot.page(title).complete(function (title, text, date) {
    //extract section '== Check ==' from wikipage&clean string
    var result = S(text).between('== Check ==', '==').s;
});

这工作。我想要的是:在其他函数中使用该代码块之外的"结果"。我认为它与回调有关,但我不确定如何处理它,因为这是mediawiki模块的预定义函数。

获取wiki页面的模块示例函数如下:

/**
     * Request the content of page by title
     * @param title the title of the page
     * @param isPriority (optional) should the request be added to the top of the request queue (defualt: false)
     */
    Bot.prototype.page = function (title, isPriority) {
        return _page.call(this, { titles: title }, isPriority);
};

,它使用模块的以下功能:

function _page(query, isPriority) {
    var promise = new Promise();
    query.action = "query";
    query.prop = "revisions";
    query.rvprop = "timestamp|content";
    this.get(query, isPriority).complete(function (data) {
        var pages = Object.getOwnPropertyNames(data.query.pages);
        var _this = this;
        pages.forEach(function (id) {
            var page = data.query.pages[id];
            promise._onComplete.call(_this, page.title, page.revisions[0]["*"], new Date(page.revisions[0].timestamp));
        });
    }).error(function (err) {
        promise._onError.call(this, err);
    });
    return promise;
}

还有一个完整的回调函数,我不知道如何使用它:

/**
     * Sets the complete callback
     * @param callback a Function to call on complete
     */
    Promise.prototype.complete = function(callback){
        this._onComplete = callback;
        return this;
    };

我怎么能访问"结果"变量通过使用模块的函数之外的回调?我不知道如何处理回调,因为它是一个预定义的模块函数…

我想要的是:在其他函数的代码块之外使用"result"。

你不能。您需要在代码块中使用结果(顺便说一下,该代码块称为callback函数)。你仍然可以将它们传递给其他函数,你只需要在回调函数中做:

bot.page(title).complete(function (title, text, date) {
    //extract section '== Check ==' from wikipage&clean string
    var result = S(text).between('== Check ==', '==').s;
    other_function(result); // <------------- this is how you use it
});