manish
manish

Reputation: 956

Running functions in sync in node.js

I want to run func2 run only after func1 has finished.

{
func1();
func2();//
}

But when func1() starts, func2() does not wait for func1() to get finished. func2() run simultaneously with func1(), which causes run time error, because func2() need some input from func1(). I also tried using async module, but got no success.

Edit: I run the function check(), which call two functions prompt() and copyProject(). copyProject() should run only after prompt() function has finished, but it start executing simultaneously.

var check = function check (){
        async.series([
            function(callback){
                prompt();
                callback(null);
            },
            function(callback){
                copyProject();
                callback(null);
            }
        ]);
};

var prompt = function prompt(){
      var prompts = [{
      name: "projectName",
      message: "What is the name of your project?"
    },{
      name: "authorName",
      message: "What is your name?",
    }];
    inquirer.prompt(prompts, function( answers ) {
      for (var key in answers) {
        if (answers.hasOwnProperty(key)) {
          console.log(key + " -> " + answers[key]);
          infoToRender[key] = answers[key]
        }
      }
});
};

var copyProject = function copyProject (){
 // code to copy some files from one location to another based on input from prompt function
};

Upvotes: 0

Views: 1295

Answers (1)

Golo Roden
Golo Roden

Reputation: 150614

Your function prompt is itself an asynchronous function: The call to inquirer.prompts causes the function to wait and this makes it asynchronous. Since your prompt function does not use a callback, the async module can not know when prompt has finished: In contrast, it runs prompt and this function immediately returns. Hence async right afterwards runs copyProject.

What you need to do to solve this issue is to introduce a callback function in prompt that async "waits" for. So basically something like this:

var prompt = function (callback) {
  // Do your stuff here...
  inquirer.prompt(prompts, function (answers) {
    // Your for loop here...
    callback(null);
  });
};

Then, within async you need to do:

async.series([
  function (callback) {
    prompt(callback);
  },
  function (callback) {
    copyProject();
    callback(null);
  }
]);

Then copyProject is only run when prompt has been completed. Please note that async.series will not wait for copyProject to finish, in case this is an asynchronous function, as again, it does not take a callback. So same pattern applies here.

Upvotes: 3

Related Questions