I am new to JS and Node and I am attempting to call a function multiple times, where each call is executed after the previous call. Part of my function uses a write stream to create a text file, so I am using a .on('finish', function(){ ...
so the remainder of my function is executed only once my text file has been created. I want to run my function over multiple files, but the whilst
loop repeats before waiting for the 'finish'
event, which causes issues.
My goal is to not repeat the whilst loop until the function embedded in the .on
is executed. My thoughts were that upon a success I could emit a custom event that executes the callback for the whilst loop at the end of the function embedded in the .on
call. However when I attempt a simply executing the callback within a custom event, I encounter the following error: if (fn === null) throw new Error("Callback was already called.");
, although it appears to run multiple times.
I've included a simplified version of the custom event I'm attempting to call. If someone can either: help me fix the code below, or show me a different method for accomplishing my original goal that'd be greatly appreciated.
var events = require('events');
function RestartLoop(fileName) {
this.fileName = fileName;
events.EventEmitter.call(this);
this.restart = function(){
console.log('ending loop');
this.emit('restart')
}
}
RestartLoop.prototype.__proto__ = events.EventEmitter.prototype;
var callbackLoop = new RestartLoop('example file name');
async.whilst(
function(){ return j < 3; },
function(cb) {
console.log(j);
j++;
callbackLoop.on('restart', function(){
cb();
});
callbackLoop.restart();
},
function(err) { console.error("we encountered an error", err); }
);
via Charlie Griffin
No comments:
Post a Comment