0

I'm trying to get my head around callbacks in Node.JS and it's pretty foreign compared to what I'm used to.

I have the following example from another post on here:

var someOutput;

var myCallback = function(data) {
  console.log('got data: '+data);
  someOutput = data;
};


    var usingItNow = function(callback) {
  callback('get it?');
};

//now do something with someOutput outside of the functions

I have added the someOutput variable - I want to get the text 'get it?' (obviously I don't) into there so that I can concatenate it on to a string, but it's not working in any combination I've tried.

I must be missing something fundamental here!

Thank you for the help.

2
  • 1
    call usingItNow(myCallback); Commented Oct 24, 2017 at 8:44
  • Haha, thank you. It seems like a pretty stupid question now! Commented Oct 24, 2017 at 8:45

2 Answers 2

1

You should call the function:

usingItNow(myCallback);

But anyway it is not a good practice to use callback to set variable and consume later. It will work for you now, but later if callback will be async, it will fail.

Consider using Promise and use someOutput in the then function. A good Promise package is Bluebird

If you want to do it like a pro, consider using Promise.coroutine http://bluebirdjs.com/docs/api/promise.coroutine.html

Or async + await if you are using an updated version of Node.js

Look on http://node.green/#ES2017-features-async-functions to check what avilable on your node version

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

2 Comments

I feel like that might have just happened - I'm trying to call a web service inside the function and someOutput is coming back undefined - I'll try your suggestion. Thanks!
Exactly the case. I'll some more explanation in my answer
0

As commented by emil:

"call usingItNow(myCallback);"

doh!

Comments

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.