首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在NodeJS中将对象传递给子文件的最佳方法是什么?

在NodeJS中将对象传递给子文件的最佳方法是什么?
EN

Stack Overflow用户
提问于 2016-03-01 16:54:13
回答 2查看 120关注 0票数 3

例如,我有这样的代码:

代码语言:javascript
复制
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传递给这些回调的最佳方式是什么?

代码语言:javascript
复制
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中有没有可能或者可能有一些特定的技术?

EN

回答 2

Stack Overflow用户

发布于 2016-03-01 17:11:27

将redis上的所有操作保存在一个名为redisoperation.js的单独文件中如何?

代码语言:javascript
复制
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

代码语言:javascript
复制
// 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 doc

模块在第一次加载后被缓存。这意味着(尤其是)每次调用require('foo')都会得到完全相同的对象返回,如果它解析到相同的文件的话。

正如你的评论指出的那样,没有redisoperation.js的多个副本。

票数 2
EN

Stack Overflow用户

发布于 2016-03-01 17:00:23

如果您的search函数是在当前模块中定义的,那么使用client的最好方法就是将其定义为模块根级别的变量。

在我看来,最好的方法是使用Promise。使您的搜索方法返回promise,然后在当前模块中为该promise定义一个回调。它看起来像这样:

代码语言:javascript
复制
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,搜索方法将类似于:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35718357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档