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

时间:2020-12-08 11:35:32

I am trying to send API calls to a NodeJS server. Unfortunately, the server (that was not made by me) won't allow me to make async calls.

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

I am trying to figure out a way to make every request to wait for the previous request to finish before being sent.

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

Here is my code:

这是我的代码:

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();
    });

}

I was thinking I could nest a while loop inside the for loop, and the while loop would have a flag that would dictate when the for loop could keep going.

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

Now, this code works when I hardcode the value of url as a single url, so i know that I am successful in sending and receiving.

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

Thanks for all/any help!

感谢所有/任何帮助!

1 个解决方案

#1


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();

Update: This is another way of doing the same thing.

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

/**
 * 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();

#1


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();

Update: This is another way of doing the same thing.

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

/**
 * 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();