0

I have a global variable 'results' which is a string that will be used by two functions that run a process and append their output to the 'results' variable. However, the functions take time to process and return the result. Following is the current format of the code.

var results = 'Results: ';

router.get('/',function(req,res){

   app1.processImage(path, function(err, output){
   console.log('app1 processing completed');

   results = results+'app1 result:' + output;
  });

   app2.processImage(path, function(err, output){
   console.log('app2 processing completed');

   results = results+'app2 result:' + output;
  });

 console.log('Both processes are completed');

 console.log(results);// none of the results printed.

});

When I try to print the results, it doesn't have the outputs yet. the program produces output like this

current output:

Both the processes are completed

Results:

app2 processing completed

app1 processing completed

Expected output:

app1 process completed

app2 process completed

Both the processes are completed

Results: app1 result : true , app2 result:true

Notice that the current output results are empty as the functions are not processed yet. How can I get the results properly stored in the variable?

Trinadh venna
  • 475
  • 3
  • 11
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Mar 02 '17 at 23:08

1 Answers1

0

This is a race condition. You should look into using Promises. With promises you will be able to let your script wait before executing the next item using .then() or .done()

Moose
  • 1,270
  • 2
  • 19
  • 33