2016-03-01 71 views
3

對於exmple我有這樣的代碼:將對象傳遞給NodeJS中的子文件的最佳方法是什麼?

var redis = require('redis'); 
var client = redis.createClient(port, host); 

var Stash = require('./lib/stash'); 
var stash = new Stash(data); 

stash.search() 

search方法中包含幾個request的在回調,我需要的數據保存到Redis。將client傳遞給回調函數的最好方法是什麼?

Stash.prototype.search = function(search) { 
    var self = this; 

    request(SEARCH_URL + '?' + querystring.stringify(this.params), function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
      // Here i need REDIS 
     } 
    }); 
}; 

通過search方法作爲參數,然後添加到回調?基本上我需要在不止一個地方有Redis,所以我需要做的就是像PHP中的靜態類。有沒有可能或可能在NodeJS有一些具體的技術?

+0

我認爲你應該在你的配置級別啓動Redis連接。所以像'config.redis'這樣的東西永遠都是同一個對象,而不是每次都是一個副本或一個新對象。 – Aukhan

回答

1

如果您的search函數是在當前模塊中定義的,那麼使用客戶端將不會有更好的方式,而只是將其定義爲模塊根級別的變量。

就目前而言,我認爲最好的方法是使用Promise。使其搜索方法返回一個承諾,然後在當前模塊中定義該承諾的回調。它應該是這樣的:

stash.search().then(function(results) { 
    //saveStuff is the made-up function. Use your redis API here to save stuff. If your saving logic was inside the search function before, you were doing something wrong. 
    client.saveStuff(results); 
}) 
.except(function(err) { 
    //This is the reject handler. 
    console.log(err); 
}); 

如果你使用ES6的承諾,尋求方法將是這個樣子:

function search() { 
    //Resolve and reject are functions that mark promise as completed successfully or with error respectively. You can pass some data into them. 
    return new Promise(function(resolve, reject) { 
    //This is your async search logic (using request module). 
    request('http://www.google.com', function (error, response, body) { 
     if (!error && response.statusCode == 200) { 
     //You may wanna transform response body somehow. 
     resolve(body); 
     } else { 
     reject(error); 
     } 
    }); 
    }); 
} 

您可以閱讀ES6更多信息有望在這裏:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

+0

正如我在搜索方法中提到的是https://github.com/request/request,我需要使用'redis'回調,而不是'search'它自己。 – user1564141

+0

此技術與您使用的模塊沒有任何關係。承諾可以用來簡化非常異常的工作。我已經向您展示了您可以在代碼中使用它們的最基本方式。 –

+0

所以基本上,當我在回調中調用'resolve(body);'時,它會在我的主文件中調用'then' – user1564141

2

如何在redis上保留所有的操作在一個名爲redisoperation.js的獨立文件中。

var redis = require('redis'); 
var client; 
exports.init = function init() { 
    if (typeof client === 'undefined') { 
     client = redis.createClient(port, host); 
     client.on("ready", connectionEstablished); 
     client.on("error", connectionError); 
     client.on("end", connectionLost); 
    } 
} 

exports.saveDataToRedis = function (data) { 
    // save data to redis through client 
} 

exports.getDataFromRedis = function (key) { 
    // get data from redis through client 
} 

App.js

// init the redis connection firstly 
var rd = require('./redisoperation.js'); 
rd.init(); 

// other operation on redis through `rd.saveDataToRedis(d)` or `rd.getDataFromRedis(k)` 

也爲它要使用redis相關API的其他文件,可能需要redisoperation.js如上,並調用它們。


require doc

模塊他們是第一次加載後會被緩存。這意味着(除其他外)每次調用require('foo')時都會返回完全相同的對象,如果它解析爲相同的文件。

redisoperation.js沒有多個副本作爲您的評論指出。

+0

但是在這種方式,我將有多個同一個對象的副本。在我的情況下,我將有11個連接到'Redis',因爲我有11個不同的模塊。 – user1564141

+0

@ user1564141,你的意思是require('./ redisoperation.js');'可以製作該對象的多個副本?如果是這樣,則只需從緩存中獲取該對象。 '模塊在第一次被加載後被緩存。這意味着(除其他外)每次調用require('foo')將返回完全相同的對象,如果它解析爲相同的文件。請參閱此文檔[https://nodejs.org /api/modules.html) – zangw

+0

好的,我不知道,但是當我每次調用init時都會執行它中的代碼時仍然如此?或者我需要在主文件中調用init來初始化並在子文件中使用set/get方法? – user1564141

相關問題