【问题标题】:node js - session object节点 js - 会话对象
【发布时间】:2017-08-29 15:50:42
【问题描述】:

我在 node/express 中有一个非常简单的应用程序,一旦用户连接,运行 http 到另一台服务器,对接收到的数据进行一些计算并响应用户。

现在,因为服务器到服务器的数据流动和所需的计算是此流程的瓶颈,我不想为每个连接到我的应用程序的用户重做这项工作。

有没有办法只为第一个用户执行此 http 请求及其后续计算,然后为每个后续用户重复使用?

一些代码

var app = null;
router.get('/ask', function(req, res, next) {
...
dbService.select('apps',appId).then(function(data,err,  header){
    app = data.rows[0].doc;     

    app.a1.forEach(function(item, index){
      app.a1[index]['nameSpellchecker'] = new natural.Spellcheck(item.synonyms);
    });

    app.a1.forEach(function(item, index){
      app.a2[index]['nameSpellchecker'] = new natural.Spellcheck(item.synonyms);
    });

    ...
    res.status(200).send(JSON.stringify(response));
})

基本上我想要保留的是app对象

谢谢,洛里斯

【问题讨论】:

  • 你能分享你的代码吗?
  • 另外,您要针对多少并发用户?用户等待什么样的计算是时间敏感信息,例如让 4 个并发用户连接到您的服务器。假设队列在用户 1、用户 2、用户 3、用户 4 中,计算只会发生在用户 1,如果计算结果将在用户 2、用户 3、用户 4 之间共享。这不会向其他用户提供过时的数据吗?
  • Let's Info 对时间不敏感,我稍后会解决这个问题...我在这里发现了一些有趣的东西stackoverflow.com/questions/19925857/… 我想在请求而不是模块之间共享 objs...谢谢大家!跨度>

标签: javascript node.js express


【解决方案1】:

在共享范围内创建一个变量。

当有连接时,测试变量是否有值。

如果没有,则为其分配一个 Promise,该 Promise 将使用您想要的数据进行解析。

然后添加一个then 处理程序以从中获取数据并执行您想要的操作。

var processed_data;

function get_processed_data() {
  if (processed_data) {
    return; // Already trying to get it
  }

  processed_data = new Promise(function(resolve, reject) {
    // Replace this with the code to get the data and process it
    setTimeout(function() {
      resolve("This is the data");
    }, 1000);
  });

}

function on_connection() {
  get_processed_data();

  processed_data.then(function(data) {
    // Do stuff with data
    console.log(data);
  });
}

on_connection();
on_connection();
on_connection();
setTimeout(on_connection, 3000); // A late connection to show it still works even if the promise has resolved already

然后,您有一个 promise 负责为每个连接获取数据,并将缓存它以供后续连接使用。

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 2015-12-15
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多