Neoares
Neoares

Reputation: 439

Blocking javascript functions (node.js)

I have this code:

var resources = myFunc();
myFunc2(resources);

The problem is that JavaScript calls myFunc() asynchronous, and then myFunc2(), but I don't have the results of myFunc() yet.

Is there a way to block the first call? Or a way to make this work?

Upvotes: 1

Views: 86

Answers (3)

mshell_lauren
mshell_lauren

Reputation: 5236

The reason why this code doesn't work represents the beauty and pitfalls of async javascript. It doesn't work because it is not supposed to.

When the first line of code is executed, you have basically told node to go do something and let you know when it is done. It then moves on to execute the next line of code - which is why you don't have the response yet when you get here. For more on this, I would study the event-loop in greater detail. It's a bit abstract, but it might help you wrap your head around control flow in node.

This is where callbacks come in. A callback is basically a function you pass to another function that will execute when that second function is complete. The usual signature for a callback is (err, response). This enables you to check for errors and handle them accordingly.

//define first
var first = function ( callback ) {
    //This function would do something, then
    // when it is done, you callback
    // if no error, hand in null
   callback(err, res);
};

//Then this is how we call it
first ( function (err, res) { 
    if ( err ) { return handleError(err); }

    //Otherwise do your thing
    second(res)
});

As you might imagine, this can get complicated really quickly. It is not uncommon to end up with many nested callbacks which make your code hard to read and debug.

Extra:

If you find yourself in this situation, I would check out the async library. Here is a great tutorial on how to use it.

Upvotes: 3

Dr. McKay
Dr. McKay

Reputation: 2977

Without knowing more about your environment and modules, I can't give you specific code. However, most asynchronous functions in Node.js allow you to specify a callback that will be called once the function is complete.

Assuming that myFunc calls some async function, you could do something like this:

function myFunc(callback) {
    // do stuff
    callSomeAsyncFunction(callback);
}

myFunc(myFunc2);

Upvotes: 1

Brad
Brad

Reputation: 163272

myFunc(), if asynchronous, needs to accept a callback or return a promise. Typically, you would see something like:

myFunc(function myFuncCallback (resources) {
    myFunc2(resources);
});

Upvotes: 2

Related Questions