1

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?

1

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

yes, but how i could get the s value outside callback function?
Not quite sure what you're asking. Any code that relies on the result of the 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.
To cut a long story short: You can't - at least not without additional helpers such as the already mentioned async module.
1

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);

2 Comments

good but is there is another way to get s value outside callback function?
call external function, emit event or wait some time with setTimeout (not the best way)
1

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.

1 Comment

it seams that this is the only way to achieve result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.