4 ms·
> This is because node is nonblocking. It doesn't wait for get_username() to return before continuing. You misunderstand how non-blocking works. In this case,
by aGHz 14y ago
> This is because node is nonblocking. It doesn't wait for get_username() to return before continuing.
You misunderstand how non-blocking works. In this case, it -most definitely- waits for get_username() to return before continuing. If get_username itself does some asynchronous calls (like db.query), that's its problem, but execution absolutely waits for your own functions to finish.
I'd recommend reading up more on event-driven programming.
- blhack 14y agoGreat, could you point me somewhere to learn more about the topic?
- aGHz 14y agoSorry, nothing off the top of my head, but a good starting point would be googling for stuff like "node event driven" or maybe "event driven programming" in general.
- blhack 14y agoNot sure if you're still monitoring this thread [no HN notifications, eh?], but here's my question: My get_username() function, say I have this code: var server = http.createServer(function(req, res) { username = get_username(); res.writeHead(200); res.write("<html>"); res.write("You are " + username); res.end("bye"); This obviously won't work, res.end() gets fired long before my DB query in get_username() finishes. How else would I accomplish what I'm trying to do here other than putting my response stuff in the DB query's callback function? <Sorry for the newb question, buy what I'm doing: having the response generated inside of the query's callback, seems to be the way most of these node tutorials suggest.>
- aGHz 14y agoManually, you could structure it in several functions like prepare_response() and render_response(), possibly with other functions in-between for the various chunks of data you need in your response. When all the chunks are ready, you finally call render_response() and send it. In practice, you can find a ton of libraries that can help you manage this [1], I -believe- the most recommended one would be 'futures'. [1] https://github.com/joyent/node/wiki/modules#wiki-async-flow https://github.com/joyent/node/wiki/modules#wiki-async-flow