如何发出请求等待先前的请求完成?

时间:2016-05-10 23:21:00

标签: javascript node.js api rest asynchronous

我正在尝试将API调用发送到NodeJS服务器。不幸的是,服务器(不是由我制作)不允许我进行异步调用。

我正在试图找出一种方法,让每个请求在发送之前等待上一个请求完成。

这是我的代码:

var http = require('http');
var fs = require('fs');

// An object of options to indicate where to post to
var post_options = {
    host: 'localhost',
    port: '8080',
    path: '/api/scan',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    }
};
var array = ["ssl.com", "google.com", "hamzakhan.org"];
for (var i=0; i<array.length;i++) {
    //console.log(array[i]);
    var post_req = http.request(post_options, function(res) {
        res.setEncoding('utf8');
        var body = '';
        res.on('data', function(chunk) {
            body += chunk;
        });
        res.on('end', function() {
            body = JSON.parse(body);
            // Make sure it's working
            console.log(body.response.subject);
        });
    });

    var url = array[i];
    var catURL = { "url": url, "path": "/", "port": "443", "live_scan": "false", "advanced": "true" };
    post_req.write(JSON.stringify(catURL), function(err) {
        //console.log(err);
        post_req.end();
    });

}

我原以为我可以在for循环中嵌入一个while循环,而while循环会有一个标志,指示for循环何时可以继续运行。

现在,当我将url的值硬编码为单个网址时,此代码有效,因此我知道我成功发送和接收。

感谢所有人/任何帮助!

1 个答案:

答案 0 :(得分:0)

/**
 * Disclaimer: I did not test your code. I simply added a few
 * lines to illustrate my suggestion.
 */

var http = require('http');
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;

// An object of options to indicate where to post to

var post_options = {
    host: 'localhost',
    port: '8080',
    path: '/api/scan',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    }
};

var array = ["ssl.com", "google.com", "hamzakhan.org"];
var emitter = new EventEmitter();
var counter = 0, n = array.length;

function PostRequest() {
    var post_req = http.request(post_options, function(res) {
        res.setEncoding('utf8');
        var body = '';
        res.on('data', function(chunk) {
            body += chunk;
        });
        res.on('end', function() {
            body = JSON.parse(body);
            // Make sure it's working
            console.log(body.response.subject);

            // ADD THE CALLBACK 
            // OR 
            // TRIGGER EVENT
            return emitter.emit('ResponseEnded');

        });
    });

    var url = array[counter];
    var catURL = { "url": url, "path": "/", "port": "443", "live_scan": "false", "advanced": "true" };
    post_req.write(JSON.stringify(catURL), function(err) {
        //console.log(err);
        post_req.end();
    });
}

emitter.on('ResponseEnded',function() {
    ++counter;
    if (counter < n) {
        PostRequest();
    }
    else {
        console.log('Nothing more request');
    }
});

// Start with the first request
PostRequest();

更新:这是做同样事情的另一种方式。

/**
 * Disclaimer: I did not test your code. I simply added a few
 * lines to illustrate my suggestion.
 */

var http = require('http');
var fs = require('fs');


// An object of options to indicate where to post to

var post_options = {
    host: 'localhost',
    port: '8080',
    path: '/api/scan',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    }
};

var array = ["ssl.com", "google.com", "hamzakhan.org"];
var counter = 0, n = array.length;

function PostRequest() {
    var post_req = http.request(post_options, function(res) {
        res.setEncoding('utf8');
        var body = '';
        res.on('data', function(chunk) {
            body += chunk;
        });
        res.on('end', function() {
            body = JSON.parse(body);
            // Make sure it's working
            console.log(body.response.subject);

            // THIS IS ANOTHER WAY OF DOING IT
            ++counter;
            if (counter < n) {
                /**
                 * This is were your start new 
                 * requests
                 */
                PostRequest();
            }
            else {
                console.log('Nothing more request');
            }            

        });
    });

    var url = array[counter];
    var catURL = { "url": url, "path": "/", "port": "443", "live_scan": "false", "advanced": "true" };
    post_req.write(JSON.stringify(catURL), function(err) {
        //console.log(err);
        post_req.end();
    });
}

// Start with the first request
PostRequest();