【问题标题】:Access parameter of Node.js module functionNode.js 模块函数的访问参数
【发布时间】:2015-09-21 09:14:10
【问题描述】:

我对 node.js 完全陌生,我找不到类似的问题来解决我的问题。我敢肯定你们中的一个人很容易解决……至少我猜是这样。

我正在尝试使用 node.js 的 npm mediawiki 模块获取 wikipage 的特殊段落!我使用以下预定义函数获取段落:

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

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

获取wikipage模块的示例函数如下:

/**
     * 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;
    };

如何通过在模块函数之外使用回调来访问“结果”变量?我不知道如何处理回调,因为它是模块的预定义函数...

【问题讨论】:

标签: javascript node.js callback mediawiki-extensions


【解决方案1】:

我想要的是:在其他函数中使用该代码块之外的“结果”。

你不能。您需要在该代码块内使用结果(该代码块称为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
});

【讨论】:

    猜你喜欢
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2018-01-28
    • 1970-01-01
    • 2015-03-29
    相关资源
    最近更新 更多