CatherineAlv CatherineAlv - 9 months ago 41
Javascript Question

How can I make the same function execute with javascript promises?

I want to execute the same function three times using Javascript promises. Each time the function is called a text file is read line by line and the answer for each line is written to another text file. I want javascript promise to wait till the previous function is done, but for some reason it just runs the three functions at once, thereby writing to three files at once. Since I'm processing a massive file, writing to three text files at once takes a long time.

Can anyone please help me figure out how to run this correctly? I'm new to Promises, and need all the help I can get.

Here is my 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]){
fs.appendFileSync('../paymo_output/'+fileName +'.txt',functionName(obj,id1,id2,depth)+"\n", "UTF-8",{'flags': 'a'});
fs.appendFileSync('../paymo_output/'+fileName+'.txt', "unverified"+"\n", "UTF-8",{'flags': 'a'});
console.log("ON TO THE NEXXTTTTT")

return "output2";})
return "output3";})
return "FINITO!!!";})

Answer Source

if you want to use Promises to wait until a function has finished its job, you'll need to do three things:

  1. return an unresolved Promise object from that function
  2. inside that function, resolve the Promise once you decide the function has finished its job
  3. wherever you call that function, you need to wait for its Promise to resolve before doing more things. That's accomplished with .then().

in other words:

function myFunction(input) {
   var promise = new Promise();

   /* do some things, then: */
   someEventEmitter.on('myEvent', function() {
     promise.resolve(returnValue); // all done!

   return promise;

  .then((function(result) { // run this function once the Promise has resolved
    console.log('myFunction returned: ' + result);

if you want to use Promises to do several asynchronous things in sequence, you'll need to do what's called promise chaining:

myFunction(input1) // returns a Promise, which has a .then() method
  .then(function(result) {
    console.log('first result: ' + result);
    return myFunction(input2); // return a new Promise from inside of the function passed to .then()
  }) // this new Promise has a .then() method of its own
  .then(function(result2) {
    console.log('second result: ' + result2);
    return myFunction(input3);
  .then(function(result3) {
    console.log('third result: ' + result3);