Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

多次相同GET请求,查询一次

$
0
0

query-once

Multiple times the same GET request, just query once 多次相同的GET请求,在第一次请求没有返回之前,后续又来了相同的请求,那么仅仅查询一次数据。express中间件。使用中发现什么问题,欢迎大家及时提问。

How to install

npm i --save query-once

Usage

server.js

var express = require('express');
var queryOnce = require('query-once');
var app = express();

function result(data) {
    //this === res
    this.send(data);
}

app.get('/', queryOnce.register(result), function (req, res) {
    if (queryOnce.isComplete(req)) {
        console.log('>>>>>>' + 'only once');
        setTimeout(function () {
            var data = {"query": "once"};
            queryOnce.success(req, data);
        }, 2000)
    }
});

app.listen(3000);

request.js

var http = require('http');
for (var i = 0; i < 5; i++) {
    (function (i) {
        console.time('time:' + i);
        http.get('http://localhost:3000?a=a&b=b', function (res) {
            if (res.statusCode === 200) {
                var rawData = '';
                res.on('data', function (chunk) {
                    rawData += chunk
                });
                res.on('end', function () {
                    console.timeEnd('time:' + i);
                    console.log(rawData);
                });
            } else {
                res.resume();
            }
        }).on('error', function (e) {
            console.log("Got error:" + e.message);
        });
    })(i)
}


Viewing all articles
Browse latest Browse all 14821

Trending Articles