0

I have this code

App.Model('users').find(function (err, users) {
        users.forEach(function(user) {
        console.log(user.username);
    });
});

//make usernames availible here.

This console logs the usernames. Instead of just logging to the console I want make use of the data.

But How can do this?

Thanks

7
  • You want to make use of the data? What does that mean? Do you want to build a list of usernames? Or maybe a list of user objects? Commented Jun 11, 2012 at 21:08
  • assign to a variable so that can display on the screen for example. Commented Jun 11, 2012 at 21:10
  • 3
    Welcome to the wonderful world of async! You can't do that. Commented Jun 11, 2012 at 21:10
  • You need to adapt to the callback style of programming or drop node.js :) Commented Jun 11, 2012 at 21:11
  • "Welcome to the wonderful world of async! You can't do that." CLASSIC. Commented Jun 11, 2012 at 21:11

2 Answers 2

1

They will never be available where you want them. This isn't how async/node.js programming works.

Possible:

App.Model('users').find(function (err, users) {
    users.forEach(function(user) {
        myCallBack(user);
    });
});

var myCallBack = function(user) {
    //make usernames availible here.
    //this will be called with every user object
    console.log(user);
}

Other possibilites: EventEmitter, flow controll libraries (e.g. async).

If you have written code in other languages before you need to be open to take a complete new approach how data will be handled.

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

Comments

0

With node js you don't do:

//make usernames availible here.

You do:

App.Model('users').find(function (err, users) {
    //usernames are available here. Pass them somewhere. Notify some subscribers that you have data.
});

//The code here has executed a long time ago

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.