例如,我有这样的代码:
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方法作为参数,然后添加到回调中?基本上,我需要在多个地方有静态类,所以我需要在PHP中做一些类似静态类的事情。在NodeJS中有没有可能或者可能有一些特定的技术?
发布于 2016-03-01 17:11:27
将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相关接口的文件,可以像上面那样需要redisoperation.js,并调用它们。
模块在第一次加载后被缓存。这意味着(尤其是)每次调用
require('foo')都会得到完全相同的对象返回,如果它解析到相同的文件的话。
正如你的评论指出的那样,没有redisoperation.js的多个副本。
发布于 2016-03-01 17:00:23
如果您的search函数是在当前模块中定义的,那么使用client的最好方法就是将其定义为模块根级别的变量。
在我看来,最好的方法是使用Promise。使您的搜索方法返回promise,然后在当前模块中为该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 promises,搜索方法将类似于:
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 promises的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://stackoverflow.com/questions/35718357
复制相似问题