i have a problem with sync using fs.readfile, they are not inicializing at the first time, if i try request again, then i have results. I know i can use promise and i find something useful with Q from Kriskowal. I tried it but without success. I didn´t understand very well how to implement it. If someone can help with this, i will be eternally grateful.
code:
"use strict"
var Q = require('q');
var fs = require('fs');
var arrayZipBand = [];
var jsonZipCode = [];
var arrayParsedZipcodeBr = [];
exports.parse = function(opts) {
if (opts.zipBand.constructor != Array) {
opts.zipBand = [opts.zipBand];
}
if (opts.location.constructor != Array) {
opts.location = [opts.location];
}
if (opts.config === 0) {
opts.zipBand.forEach(function(file) {
fs.readFile(file, 'utf8', function(err, logData) {
if (err) throw err;
let text = logData.toString();
decodeURIComponent(text);
let lines = text.split('\n');
lines.forEach(function(line) {
let parts = line.split('@');
if (parts[1] != undefined) {
let obJson = {
LOC_NU: parts[0],
LOC_CEP_INI: parts[1],
LOC_CEP_FIM: parts[2]
}
arrayZipBand.push(obJson);
}
});
});
});
opts.location.forEach(function(file) {
fs.readFile(file, 'utf8', function(err, logData) {
if (err) throw err;
let text = logData.toString();
decodeURIComponent(text);
let lines = text.split('\n');
lines.forEach(function(line) {
let parts = line.split('@');
if (parts[1] != undefined) {
for (let i = 0; i < arrayZipBand.length; i++) {
if (parts[0] == arrayZipBand[i].LOC_NU) {
jsonZipCode.push(arrayZipBand[i]);
}
}
if (jsonZipCode === undefined) {
throw "Was not possible to find Zipcode for the id " + parts[0];
}
for (let i = 0; i < jsonZipCode.length; i++) {
let obJson = {
LOC_NU: parts[0],
UFE_SG: parts[1],
LOC_NO: parts[2],
MUN_NU: parts[8],
LOC_CEP_INI: jsonZipCode[i].LOC_CEP_INI,
LOC_CEP_FIM: jsonZipCode[i].LOC_CEP_FIM
}
arrayParsedZipcodeBr.push(obJson);
}
jsonZipCode = [];
}
});
});
});
};
return arrayParsedZipcodeBr;
}
uhm it seems you are trying to read files in the loop cycle then, but in a async way. First question, is why async reading those files? You can always read them in sync way:
By the way, if you wish to read them async and keep the for...loop you need something like a Promise, or a timed wait or a more complex synchronization mechanism.
You can keep it simple, without using any other packages/modules in this way:
so you can call it like
Keep in mind that this is a very simplified approach, but in most of cases it works when cycling through arrays.
Here is a simple working example in the playground:
Finally, a complete asynchronous example, showing how to defer execution of a XMLHttpRequest, when cycling through a list. The
ExecutionBlock
is callingreject
andresolve
after the SimpleRequest responds, causing the Promise the wait its execution before calling thethen
.