-1

I´m sure that this is a easy issue, but i don't know how i can solve it.

I have two functions and an object in javascript (nodejs) like this:

var auxmap = new Map();
  function one(){
   for(var i...){
     //init map and do something
     two(i,params);
   }

 }
  function two(i,params){
     //create array from params called auxarray
   map(i) = auxarray
 }

my question is if i can do that function one wait until function two finish it execution, like in a C# program and how i can do that.

  • 2
    Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) It's not at all clear what you're asking. What do these functions do? – T.J. Crowder Jul 13 '17 at 09:55
  • 1
    As shown, `one` will absolutely wait for `two` to complete (assuming you call `one` somewhere. JavaScript is by-default synchronous. If `two` starts an *asynchronous* process and you want to wait for the result of it in `one`, **can't**: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call (but you can seem to with `async`/`await`). – T.J. Crowder Jul 13 '17 at 09:56
  • Which version of **nodejs** you are using? I assume that `function two` is asynchronous. T.J. is right that there are a lot of unclear things in your question. Maybe have a look here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – codtex Jul 13 '17 at 09:59
  • @Danmoreng: Nothing in the above is going to see that issue with `i`. It's being **passed** into `two`. No scope issue there. (But then, what's shown is, at best, pseudocode.) – T.J. Crowder Jul 13 '17 at 10:01

1 Answers1

0

Yes, you can! As you may know, node performs all it's operations asynchronously for I/O (that is one of it's main strengths). Therefore, in order to do wht you request, you should take a look at callbacks and promises. Since the community is currently moving towards promises, I will leave here this link so you can learn a bit more about them:

Javascript Promises

For your particular case, I will provide here a simple solution based on promises:

var auxmap = new Map();
function one(){
  for(var i...){
    //init map and do something
    two(i,params).then(function(){ //Function one waits for two to end
      //do something or end
    });
  }
}
function two(i,params){
 return new Promise(function(resolve, reject){
   //create array from params called auxarray
   map(i) = auxarray;
   resolve('Two finished');
 }
}

Hope this helps!

Community
  • 1
  • 1