Mostafa Darwish
Mostafa Darwish

Reputation: 283

Why assign global variable to value inside a callback function in node js return undefined in console?

Take this example

var s;
cb = function(error,result){
s = result;
}
memcached.get('hellow',cb);
console.log(s);

This give me undefined. What is wrong with my code?

Upvotes: 1

Views: 1812

Answers (3)

Prahalad Deshpande
Prahalad Deshpande

Reputation: 4767

The variable s is being initialized within a call back function. This call back function will get triggered only when memcached.get() completes getting the data for 'hellow'.

Javascript reliesy on the event loop mechanism. This means that the javascript runtime will continue executing the script until it reaches the end without blocking for any callback to occur.

As a result in your example, the javascript runtime will execute the line console.log(s) immediately after the line memcached.get('hellow',cb) without blocking. Hence console.log(s) in your case will print a valid value (other then undefined) only if the cb has executed prior to the last line.

Please move the line console.log(s) within the call back function for more consistent results.

Upvotes: 1

Vadim Baryshev
Vadim Baryshev

Reputation: 26199

You need to execute console.log after defining s because it asynchronous:

var s;
cb = function(error,result){
    s = result;
    console.log(s);
}
memcached.get('hellow',cb);

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 311975

The console.log(s); line executes before the cb function does because cb isn't called by memcached.get until result is available. This is the classic asynchronicity that occurs with any I/O operation in node.js.

Upvotes: 1

Related Questions