I made a small application that makes async calls to an api (local in this case). The target application will make a million of calls per day.
With maxSockets set to 1 I had a time of 45 seconds. With maxSockets = 10, the execution time has dropped to 40 seconds.
How can I make this code go faster please?
var request = require('request');
var mysql = require('mysql');
var async = require('async');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'testAPI'
});
var inputData = [];
for(i=1; i<=9999;i++){
inputData.push('number' + i);
}
var options = {
url: 'http://localhost/test.txt',
maxSockets: 10
};
var limit = inputData.length;
var counter = 0;
var fetch = function(file,cb){
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
var time = (new Date().getTime()/1000)
connection.query("insert into testAPI (name) values ('" + time + body +"')", function(err, rows, fields) {
if (err) throw err;
//console.log('Inserted: ' + time + body)
counter++;
});
}
})
}
async.map(inputData,fetch,function(err, results){
if ( err){
// either file1, file2 or file3 has raised an error, so you should not use results and handle the error
} else {
options.count = i;
// request(options, fetch)
// results[0] -> "file1" body
// results[1] -> "file2" body
// results[2] -> "file3" body
}
})
var checkIfFinished = setInterval(function(){
if(counter === limit){
console.log('finished')
connection.end();
clearInterval(checkIfFinished);
}
},1000)
setIntervalwhen you're using a control flow library likeasync? BTW your bottleneck in this code is likely to be the async resource rather than anything wrong with your code. \$\endgroup\$