2015-09-21 100 views
0

即時通訊完全是新的node.js,我找不到類似的問題,我的問題。我確信很容易解決你們中的一個......至少我猜。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模塊的預定義函數。

模塊得到一個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; 
    }; 

如何訪問「結果」變量通過在模塊的功能之外使用回調?我不知道如何處理回調,因爲它是一個模塊的預定義功能...

+0

可能重複[如何返回從異步調用的響應?](http://stackoverflow.com/問題/ 14220321 /如何返回來自異步調用的響應) –

回答

0

我想要的是:在其他功能的代碼塊外使用「結果」。

你不行。您需要使用該代碼塊內的結果(該代碼塊被稱爲callback函數btw。)。您仍然可以將它們傳遞到其他功能,您需要做的僅僅是它的回調函數裏面:

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 
}); 
+0

好的,我明白了!感謝您的快速幫助! – dnks23