response.write(something) doesn't work inside callback function?

I was learning NodeJS as I needed to implement a server for the GSoC project.

I faced a problem. response.write(something) was not working inside a callback function I had. I tried all sorts of things but couldn't figure out the problem. Finally I found the careless mistake I had done, that is I was having a response.end() which gets executed before my callback function. Once it was removed the code worked fine.

NodeJS's execution model has only a single process. Therefore NodeJs is using the concept of event driven asynchronous callbacks. So if you are having a slow operation like a database query even though NodeJS has a single process you will not have to wait until that operation finishes. The callback function can take care of what needs to happen once that slow operation is complete and the rest of the code will be executed without waiting for this slow operation.

 In my code I was having such a slow operation and before this operation finishes the "response.end()" which I had mistakenly put, was being executed and because of that, "response.write()" inside the callback wasn't working.

No comments:

Post a Comment