1

I am trying to pull a variable's value from a callback function. What am I doing wrong here?

var storyList = [];
var storyTemp ={};

// get list of all stories
db.getAllStoriesSet(function(err, reply) {
    if (err) throw err;
    else {
        storyList = reply;
        console.log("storylist inner: " + storyList);
    };
});
console.log("storylist outer: " + storyList);

in the above code, I am expecting the inner and outer storylist values to be same. however the outer storyList value still comes as a null list.

EDIT: to add to the question. I have initialized a variable storyList outside the async function. i am then taking the reply from the async function and putting it in the variable storyList. I was hoping to cheat my way out of the async pit of slow and brutal death that I have apparently dug for myself. shouldnt it have worked?

1 Answer 1

5

If getAllStoriesSet is asynchronous, then the line following its call is called before the callback is executed. So storyList is just like it was before the call.

That's the reason why you provide a callback : you must put inside the callback the code which needs the value of reply.

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

1 Comment

it is an async function. How can i get the value of stoyList without a callback? This whole async programming is making my life hell. :/ do i need to add another callback? The way I am daisy-chaining my async functions and callbacks, I might as well do synchronous programming.

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.