Task: I collect geodata data from the server (not mine). To do this, I form a request for a specific interval of coordinates and send a request to the server in the for loop. I write down the answer to a file and so that the server does not ban it, changing the ip address via tor-control Awaiting response is implemented using promise. This is the ideal. In fact (judging by the logs in the console), the data is sent as horrible. Tell me where I turned the wrong way.
for (var i = xMin; i <= xMax; i++) { for (var k = yMin; k <= yMax; k++) { var swp = swPoint(k, i); var nep = nePoint(k, i); var llsw = pointToLatLong(swp[0], swp[1]); var llne = pointToLatLong(nep[0], nep[1]); var datatosend = 'fromlat=' + llsw[0].toString() + 'tolat=' + llne[0].toString() + 'fromlng=' + llsw[1].toString() + 'tolng' + llne[1].toString(); currX = k; currY = i; filename = "json/" + currX.toString() + "_" + currY.toString() + "_" + zoom.toString() + ".json"; options.body = datatosend; console.log(filename); GetData(options) .then(body =>{ return WriteToFile(body, filename); }) .then(() =>{ return GetNewCircuit(); }) .then(() =>{ console.log('Step finished'); }) } }
Judging by the logs, it turns out that he sweeps through the loop 4 times without waiting for the previous operations.
Console Log Text:
json/0_0_1.json json/1_0_1.json json/0_1_1.json json/1_1_1.json Get response json/1_1_1.json Circuit changed Step finished Get response json/1_1_1.json Circuit changed Step finished Get response json/1_1_1.json Circuit changed Step finished Get response json/1_1_1.json Circuit changed Step finished
Called methods:
function GetNewCircuit(){ return new promise(function(resolve, reject){ new_identity('127.0.0.1', 9051, cookie, function(err){ if(!err){ console.log('Circuit changed'); resolve() } else{ console.log(err); reject(err); } }); }); } function GetData(reqOptions){ return new promise(function(resolve, reject){ request(reqOptions, function(error,response,body){ if(!error && response.statusCode == 200){ console.log('Get response'); resolve(body); } else{ reject(error); } }); }); } function WriteToFile(dataToWrite, fileToWrite){ return new promise(function(resolve, reject) { fs.writeFile(fileToWrite, dataToWrite, function(err) { if(!err){ console.log(fileToWrite); resolve(); } else{ reject(err); } }); }); }
I am just starting to get acquainted with js, so if, besides the answer, you can also advise where and how best to familiarize myself with it.