I'm banging my head against the wall to figure out how to push data that is being written on file asynchronously into an array. Writing the data synchronously (and checking if the item is the last on the list) takes too much time so I decided to make it run async. After doing some research, it seems that I could use a callback
I would prefer not to use an external library for doing this, since I'm pretty sure either a callback or a Promise should do the trick. Thanks!
//Iterate through list and make HTTP request to get data
dataDocument.map(function(item, index) {
request(item, function(err, res, html) {
if (err) throw err;
renderData(html, item);
});
});
//Renders data
function renderData(html, item) {
...some calculations here.
writeData(output, id, function() {
pushed(output);
});
};
//Writes the data on file
function writeData(output, id) {
fs.appendFile('./output.json', output);
//SHOULD I USE A CALLBACK HERE TO PUSH INTO AN ARRAY ONCE IT'S COMPLETE?
};
//NEED HELP HERE: Pushed the data into an array and eliminates last comma.
function pushed(data) {
var arr = [];
arr.push(data);
}
via agomez
No comments:
Post a Comment