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?
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?
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.
s value outside callback function?memcached.get must execute after the callback is called. So you can put your code that references s in the callback, or use a flow control library like async to execute another function after cb is called.async module.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);
s value outside callback function?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.