I have an issue using promises with Node.js. I am using cheerio and request-promise to do web scraping, and I want to write my results to a CSV file once all asynchronous functions have been executed, using the Promise.all(promises).then(...)
syntax. It was working fine but suddenly the program finishes without any error or rejects but without executing the then(...)
part (no file and no log neither). Here is my code:
const rp = require('request-promise');
const cheerio = require('cheerio');
const csv = require('fast-csv');
const fs = require('fs');
var results = [];
var promises = [];
function getResults(district, branch) {
for (let i = 65; i <= 90; i++) {
let letter = String.fromCharCode(i);
let generalOptions = {
uri: 'https://ocean.ac-lille.fr/publinet/resultats?previousValCri1=' + branch + '&previousValCri0=0' + district + '&previousIdBaseSession=pub_24&actionId=6&valCriLettre=' + letter,
transform: function (body) {
return cheerio.load(body);
}
};
promises.push(new Promise(function(resolve, reject) {
rp(generalOptions)
.then(($) => {
$('.tableauResultat').find('tr').each(function(i, elem) {
let children = $(elem).children('td');
let name = $(children[0]).text();
results.push({name: name, result: 42, branch: branch});
resolve();
});
})
.catch((err) => {
console.log(err);
//reject();
});
}
));
}
}
getResults(process.argv[2], process.argv[3]);
Promise.all(promises).then(() => {
console.log("Finished!");
var ws = fs.createWriteStream('results_bis.csv', {flag: 'w'});
csv.write(results).pipe(ws);
}).catch((err) => {
console.log(err);
});