How can I make the same function execute with javascript promises? -
i want execute same function 3 times using javascript promises. each time function called text file read line line , answer each line written text file. want javascript promise wait till previous function done, reason runs 3 functions @ once, thereby writing 3 files @ once. since i'm processing massive file, writing 3 text files @ once takes long time.
can please me figure out how run correctly? i'm new promises, , need can get.
here code:
function verifytransactions(filename,functionname,obj,depth){ var rd = readline.createinterface({ input: fs.createreadstream('../paymo_input/stream_payment.csv'), output: process.stdout, terminal: false }); rd.on('line', function(line) { var userdata = extractuserdata(line) if (userdata !== undefined){ var id1 = userdata[0], id2 = userdata[1]; if (obj[id1]){ console.log(id1) fs.appendfilesync('../paymo_output/'+filename +'.txt',functionname(obj,id1,id2,depth)+"\n", "utf-8",{'flags': 'a'}); } else{ console.log("nope") fs.appendfilesync('../paymo_output/'+filename+'.txt', "unverified"+"\n", "utf-8",{'flags': 'a'}); } } }); rd.on('end',function(){ console.log("on nexxttttt") }) } promise.resolve("output1") .then(function(file){ verifytransactions(file,pasttransaction,usertransactions); console.log("writing file 2 soon") return "output2";}) .then(function(file){ verifytransactions(file,breadthfirstsearch,usertransactions,2); return "output3";}) .then(function(file){ verifytransactions(file,breadthfirstsearch,usertransactions,4); return "finito!!!";}) .then(function(file){ console.log(file); })
if want use promises wait until function has finished job, you'll need 3 things:
- return unresolved promise object function
- inside function, resolve promise once decide function has finished job
- wherever call function, need wait promise resolve before doing more things. that's accomplished
.then()
.
in other words:
function myfunction(input) { var promise = new promise(); /* things, then: */ someeventemitter.on('myevent', function() { promise.resolve(returnvalue); // done! }); return promise; } myfunction(input1) .then((function(result) { // run function once promise has resolved console.log('myfunction returned: ' + result); });
if want use promises several asynchronous things in sequence, you'll need what's called promise chaining:
myfunction(input1) // returns promise, has .then() method .then(function(result) { console.log('first result: ' + result); return myfunction(input2); // return new promise inside of function passed .then() }) // new promise has .then() method of own .then(function(result2) { console.log('second result: ' + result2); return myfunction(input3); }) .then(function(result3) { console.log('third result: ' + result3); });
Comments
Post a Comment