0

In node.js I need to collect some data across multiple callbacks and store them in one object. I tried the following code, but the collected data is not saved in the initialized variable. Can you pls help what I'm doing wrong?

My code:

for (var x in data) {
    var status = {items: []};

    for (var y in x) {
        do_something(y, function (err, res) {
            again_do_something(res, function(err, result) {
                status.items.push({key: result});
            });
         });
     }

     console.log(status); //Here I got only {items: []}
}
0

1 Answer 1

3
console.log(status);

will be getting executed before the callback function getting executed. Thats why you are seeing empty.

One easy way to solve this common problem is to use async library's concat method.

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

2 Comments

Thanks! I've missed that. But then how can I track down when has the last callback been executed so I can pass the collected data forward?
@filo891 Updated my answer with async library solution. Please check.

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.