Sara
Sara

Reputation: 489

Wait for the end of a function before starting another one in JavaScript

I'm just a beginner in JavaScript, and I would like to wait for the end of an action before executing the next one. I've already searched an answer to my problem on Google, but all I've found are the using of callbacks to string functions together. OK, but that is not what I need. I don't want to make a chain, I want to make an imbrication, like this :

function f1() {
    function f2() {
        function f3() {
            return result;
        }
    return result;
    }
return result;
}

So that, when I call console.log(f1), it prints the results which is calculated in f3(). Is there a simple way to do this ?

Thank you.

Sara.

EDIT: Well, I think I have to give a better example ! In concrete terms, I work on a web server with express and a a database with mongoose and mongodb. I have four types of path : path concerning jobs, groups, workers and users. When I get a page, I have to get the right list of elements in the database to display : if I go on the page /job, I get the list of existing jobs, if I go on the page /user, I get the list of existing users, etc. In the routing file, I call another file which will manage the connection to the database. Here are my codes :

In the file route.js :

var mongo = require('./mongo');
exports.list = function(req, res) {
    var data = mongo.read(req.params.type);//the type of element we are looking for (jobs, user...)
    res.render('liste', {
        table: data; //In the view, we get table.name, table.status, for each element of the table
    }
}

In my mongo.js :

exports.read = function(type) {
    var result;
    start(); //It's the function which start the database, create the schemas, etc...
    if(type == 'job')//4 conditions, in which we get the right model (in the var model) according to the page we're looking for
    model.find(function(err, data) {
        if(err) { ... }
        else {
            result = data;
        }
     }

     return result; //It return nothing, because it do this before doing the model.find(...)
}

I hope it is clearer.

EDIT (again...) : Thank you everybody for your answers and thank you Sagi Isha for giving me the solution :)

Upvotes: 1

Views: 2369

Answers (5)

Sagish
Sagish

Reputation: 1065

according to your node/express code: Node work asynchornocally, which means you need to pass callbacks to I/O operations,

i.e

var mongo = require('./mongo');
exports.list = function(req, res) {
  mongo.read(req.params.type, function(err, data){
    if (err) {return console.error(err)}
    res.render('liste', {table: data});
  });
}

and

exports.read = function(type, callback) {
  if(type == 'job') {
    model.find(callback);
  }
}

Upvotes: 3

Bergi
Bergi

Reputation: 664920

It sounds like you are having asynchronous code - the functions do return before they yield their result to a callback function:

function async(callback) {
    // start heavy processing
    return undefined;
    // when processing is finished,
    // callback(result);
}

Examples are setTimeout, ajax, user events etc.

If you have such behaviour in your code, you will need to pass the nested f2/f3 as callbacks to them:

function f1(callback) {
    someAsync1(function f2(resultfromAsync1) {
        someAsync2(function f3(resultfromAsync2) {
            someAsync3(callback);
        });
    });
});

To call that and log the result, you will use

f1(function(resultfromAsync3) {
    console.log(resultfromAsync3);
});

Upvotes: 0

connectedsoftware
connectedsoftware

Reputation: 7087

We would really need to know what is being done within each function but but assuming you are processing the return value of each function in the next function you could do this:

function f1(){
   var inputValue = 1;
   var result = f2(inputValue);
   result = f3(result);
   return result;
}

function f2(input){

  <!-- Do some processing -->
  return result;

}

function f3(input){

 <!-- Do some processing -->
 return result; 

}

Upvotes: 0

amd
amd

Reputation: 21482

You are looking for the Immediate function invocation :

check this code

function f1(){
 return 
   (function(){
      return 
        (function(){ return 1})()
   })()
};

console.log(f1());// prints 1

check this link for more info

Upvotes: 0

Yann86
Yann86

Reputation: 1017

In your exemple you never call the functions f2 and f3

function f1() {
  function f2() {
      function f3() {
         return result;
      }
    return f3();
   }
 return f2();
}

Upvotes: 1

Related Questions