2017-08-29 144 views
0

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

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

有什么办法可以做到这一点的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)); 
}) 

基本上我想保留什么是应用对象

感谢,洛里斯

+1

你能分享你的代码吗? – ninesalt

+1

另外,您尝试定位多少个并发用户?用户等待的是什么类型的计算是时间敏感信息,例如让4个并发用户连接到你的服务器。假设队列位于user1,user2,user3,user4,则计算将仅发生在user1上,并且计算结果将在user2,user3,user4之间共享。不会给其他用户陈旧的数据? – Raj

+0

让我们的信息不是时间敏感的,我会在以后解决......我发现在这里很有意思https://stackoverflow.com/questions/19925857/global-scope-for-every-request-in-nodejs-express我想分享请求之间的对象,而不是模块......谢谢你们! – user2428183

回答

0

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

当有连接时,测试以查看该变量是否有值。

如果不是,则为其分配一个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

你就必须负责获取数据为每个连接单独的承诺,它会缓存它的后续连接。