2026-08-22 13:36

Status:


BDAN - Module 2 - Asynchronous I-O with callback programming

==Asynchronous I/O with Callback Programming

  • Asynchronous I/O with Callback Programming:
    • Asynchronous I/O- generally network operations run in an asynchronous manner this is for the fact that whenever a response from a network service is expected, it might take a while to get there, so whenever you are trying to make a website and not have it stall, you need to have the site keep running while it waits for the response
    • Instead of just blocking everything in the service while waiting for the http response
    • Node. js does this by making all network operations in a non-blocking manner, with EVERY single network operation returning IMMEDIATELY
    • To handle the result from a network call, you can write callback functions that Node. js calls whenever the network operation completes
    • Pasted image 20260822140557.png
    • Pasted image 20260822140843.png
    • The application first makes a http.request() call over to a given node. js framework from the browser
    • Upon receiving this, the node. js framework sends it over to the remote server (which is the actual back-end code you write)
    • BEFORE node receives a response from the server, it IMMEDIATELY returns back a result to the http.request() call from earlier, this says the request message was sent successfully, but does not say SHIT about what the response was
    • Whenever node then receives the response message from the remote server it calls the callback function you defined to actually handle the web service response
    • Basically what happens is that web browser sends over a request and node immediately tells it that the request was sent after passing off the request to the back-end server, and then whenever that server actually process the data it gives the response message over to node, and then nodes starts a callback which is used to handle the response
    • In essence this is how node is able to keep things without blocking, what it does is sends back a response message immediately and lets the web browser actually continue on functioning without taking on too much processing power or computer time, while it lets the back-end code handle it’s shit and whenever it does it sends the actual real response back
    • IMPORTANT POINT OF UNDERSTANDING:
      • http.request() returns immediately TO YOUR OWN NODE. JS code, telling YOUR CODE that the request has been sent. The actual browser HTTP connection is still open and waiting because node has not sent any HTTP status code
      • Node goes off and handles the other things like the event loop
      • Then, like 5 seconds later, the back-end server responds, and Node. js triggers your callback, finally you write things like res.writeHead(200) and res.end(data) to send over the HTTP response to the browser
    • Pasted image 20260822140934.png
    • This is an example of how to SEND an HTTP request, basically you have the site that you are sending it to (the server), and then the routing path for node.
    • You send the request with http.request(), and fill in the data needed
    • This basically lets events occur while receiving parts of the HTTP response message
    • THIS IS ALL NODE CODE BTW
    • This request code basically gets parts of the HTTP request and lets you continue to do things while these small amounts of data trickle in
    • Pasted image 20260822141808.png
    • The http.request() function takes in a URL and a callback function, and then that callback function that you write is called whenever it receives a part of the HTTP response message from the back-end I suppose
    • This callback function then basically takes in a response variable as the first parameter, and this param is able to act on and do different things to this response object
    • In the above hand example, the object.on() function defines an event handler that the framework calls whenever a function occurs, telling the buffer object to increase in size by the given chunk of data that you have received from the call
    • With then also logging in that buffer or basically printing it out
    • The .end() function call I can assume is used to close the connect or at least indicate that all of the data has been sent or received
    • Pasted image 20260822142052.png
    • Pasted image 20260822142130.png
    • You can also then handle error events that might occur
    • This is done using the http.clientRequest object which lets you write the error data over whenever an error might occur, and lets you define an event handler for errors that Node. js encounters while sending the request message as well
  • Creating Callback Functions:
    • Propagating Errors given that node. js generally runs as an asynchronous framework, it makes extensive use of callback functions to return the result to the calling function so that way things are not blocked

    • Pasted image 20260822145843.pngNode.js modules pass an error object as the first parameter in a callback function

    • With the first param being the error, the callback function checks if the first parameter is in fact an error object, and if it is defined as one, then it handles the error and cleans up any open network or database connections

    • The callback function examines the result from the call if the error object is not defined

    • In the above hand example after getting the data from the weather module, you basically define the callback function with the error parameter, at which point if it is in fact defined (the two end points did not connect properly or something) then it would print out the error, otherwise it does whatever it wants with the info it gets from the module

    • This seems like a way to basically connect another API to your own back-end with node, which I thought was only a thing with front-end but I do suppose not

    • Passing an Error Object to the callback function

    • Pasted image 20260822150147.png

    • Basically inside of the http request function that was talked about in the previous video, you have the regular request.on() functions in which you define your own callback functions, but then inside of that given callback function you then have another parrseString function which takes in the buffer from the original request and then basically a callback error function as well. Therefore, if an error occurs whenever you are parsing the string, you seemingly call the function again letting it known an error occurred, passing in null if the error did not occur

    • Passing HTTP response message

      • The callback handler can print the contents of the HTTP response message body to the console or log the contents into a database, which is pretty much the server console itself
      • However you can then move this back over to the console in the web browser if you wanted to as well
    • Pasted image 20260822150655.png

    • The issue is that steps 5 and 6 inside of the diagram have no real way of knowing about one another, which makes it hard to have node send back the processed data from the remote server back over to the web application

    • The Fix: when one node. js application calls a module in a non-blocking manner, the application must provide a callback function to process the result

    • SO: if the main application calls http.request() it MUST PROVIDE a callback handler to process the HTTP response message

    • Pasted image 20260822151731.png

    • Basically what occurs is the steps 1-3 are generally just the call making it’s way over to the remote server, first the call is made from the web app, sent to the Node. js module, handled by the node framework and then sent over to the remote server

    • Then, the node framework sends back the return from h ttp.request to let the module know that the request has been sent, which then passes this back over to the application

    • Sometime later, step 6 happens where the actual request is processed by the remote server and sent over to the node framework

    • Which then, in step 7 sends it back over to the http.request() callback function, WHICH THEN RUNS ITS OWN APPLICATION CALLBACK FUNCTION

    • If the main application calls a function that calls http.request(), two callback functions are involved:

      • The custom module has a callback function to handle the HTTP response message from a http.request()
      • The main application has a callback function that processes the result that is captured in the first callback function
    • The images below are an actual step by step code example of the above theory

    • Pasted image 20260822152042.png

    • Pasted image 20260822152058.png

  • Issues with Callbacks:
    • Callback functions- a function passed an argument to another function. Inside of generally node, it seems that these are functions passed in or defined as arguments for another function that is used to basically allow a web service to keep on going and not stutter while your back-end handles the things it needs to handle, while also allowing you to do something once that handling has occurred and the response is ready to be sent back
    • They are functions that are only executed after an actual action is produced
    • Pasted image 20260822153151.png
    • Callbacks make sure that a function will NOT run before a prerequisite task is completed, in the above example, message is a callback function, that is basically going to perform a given function after a given condition is met, which in the case of node and asynchronous functions, is basically done whenever the remote server is able to handle the request
    • Generally, these async callbacks are used for retrieval or execution of data from things like databases, images, or reading files
    • In a way they are sort of like a connect of getting services from another module or whatever is providing the data kind of, not a front-end way of getting these things, but just a way of connect this already stored back-end data to your own back-end
    • These callback functions wait for a response from these above hand data forms and then proceeds to execute whenever they receive the data, with built in error handling that occurs if there is some kind of an issue
    • Pasted image 20260822153920.png
    • Sequentially structured code is generally done in a nested manner, and the reason why this is bad is because, well, look at it, nested code is in general never really a good thing
    • Each function is a callback to the next function, and therefore they are all reliant on one another this makes it hard to have good structure because if one fails, then they all crash too
    • Basically callback hell
    • Inversion of Control (IoC) is execution is external to your code, basically whenever the control or flow of your program is external and not internal
    • So basically you handle over control to an outside third party piece of software, and then if that code has errors, you are basically fried
    • You are FORCED to trust the third party code basically, which can be a large pain
    • Ways to mitigate Callback Hell & Inversion of Control
      • Write comments
      • Split functions into smaller functions
      • use promises (next note section)
      • use async/await (also further down)
  • Promises:
    • Promise- this is an object that is returned by an asynchronous method, and it has three states: pending, resolved, or rejected

    • They are useful for API requests, and I/O operations that generally are time intensive and take up a large number of computing resources

    • A method can be defined to return a promise object IF you know that it is going to take time to give you back what you need

    • This is basically used to set up something that is more asynchronous in nature and does not block the entire programming chain

    • Pasted image 20260822165018.png

    • A promise object is first returned from a promise function with a pending status, and is in this state until the given operation you are waiting for is complete

    • If the operation is complete, then you’re all good, the status is set to resolved and the data is passed on

    • If the operation is not complete, well then you get the rejected result and then you handle that however you need to

    • Pasted image 20260822165037.png

    • The above-hand code is an example of a promise function, it defines a new function with the new Promise((resolve, reject)) set up that basically sets a timeout timer for the user to type in information, giving them 30 seconds.

    • If it rejects then the promise is set to rejected, if not then it resolves the data read from that file

    • Printing out whatever happened in the console

    • Basically, this is good for things like prompts or whatever it is that you actually wait for getting information, if you know something is going to give you data, you can use a promise to not necessarily halt while waiting for data or input

    • AXIOS request

    • Pasted image 20260822165544.png

    • So, basically an HTTP request can be considered to be pretty blocking whenever you want to use one, and a lot of the http functionality of node tends to be wrapped around URL requests and what not

    • So axios is a package that is used to handle HTTP requests

    • It returns a promise object with a pending status of the object while it is waiting to hear back from the URL, with a .then method being used after it actually gets the data back, and a .catch if the promise is rejected

    • So you pass in a valid URL, and then once the promise is fullfilled, the promise can be logged to the console or whatever else

    • The main thing is this does not halt the execution time of your program, letting other things run

  • Working with Json:
    • JSON (JavaScript Object Notation) is the standard format for application programming interface (API) data exchange, basically, it holds a bunch of information in the form of easy to see and understand objects

    • It is good for exchanging data between two different native javascript objects (can be used with more than just JS tho), and is easily handled by Node.js

    • It generally consists of "Attribute" : "Value" pairs which are enclosed inside of {} with each new {} representing a new object, this is good because objects can be nested inside of each other

    • Parse JSON from HTTP message

      • JSON.parse() parses a JSON string to a JavaScript object with each given value
      • This lets you basically use the object as the storage method to access all of the data
      • Let it be known, method JSON.stringify() also lets you convert a given object or string into json format, depending on how you put it in
    • This is the bare-bones way of doing it, inside of express for example, you also have things like middle-ware with something like app.use(express.json()) which basically looks at all incoming traffic, sees if it is json, and then proceeds to parse it automatically for you

  • Promises, async/await, and axios requests in Node. js and Express:
    • Async operations basically help you give a better user experience because they allow for the website to not stutter and seem seamless to the user, meaning they are more likely to use your website again
    • Pasted image 20260822194838.png
    • Pasted image 20260822194853.png
    • Pasted image 20260822201839.png
    • Promise- basically an object that represents the eventual success or failure of an event that you have set out to do
    • They are very useful for maintaining more readable code and chaining operations together while also having code that can execute without blocking the execution flow
    • Promises are more further detailed in the above hand notes
    • Pasted image 20260822202101.png
    • Pasted image 20260822202128.png
    • Async/await are basically syntactic sugar that simplifies promises because they can tend to clutter and complicate your code as well
    • It makes it look more like synchronous code which makes it a lot easier for you to read, write, and understand
    • An async function returns a promise, so you can use await to pause execution until a promise resolves or rejects also this generally I believe would actually turn your code back into synchronous no, because it would literally pause execution
  • Promises, async/await, and axios requests in Node. js and Express (Pure Annotated Examples)
    • Pasted image 20260822202459.png
    • Pasted image 20260822202520.png
    • ![[Pasted image 20260822202542.png]]
      
    • Pasted image 20260822202559.png
    • Pasted image 20260822202611.png
    • Pasted image 20260822202628.png
    • Pasted image 20260822202640.png
    • Pasted image 20260822202655.png
    • Pasted image 20260822202718.png
    • Pasted image 20260822202730.png
    • Pasted image 20260822202750.png
    • Pasted image 20260822202804.png
    • Pasted image 20260822202824.png
  • Module Summary:
    • Asynchronous network operations can be handled using callback functions in order to prevent blocking JavaScript code  

    • A callback function must invoke another callback function to pass a message from the Node.js module back to the main application after the Node.js module receives a response message 

    • Nested callbacks can be difficult to read and debug. Inversion of control causes trust issues when dealing with third-party code 

    • Promise objects are most useful for operations that are time-consuming and can block resources 

    • JSON.parse() and JSON.stringify() are two methods used to parse JSON objects

==Glossary

TermDefinition
AsyncShort for “asynchronous”.
Axios PackageThe axios package wraps promises around HTTP requests. It returns a promise object.
Callback HellMany nested callback functions.
Inversion of ControlWhen the flow of control, such as the execution of instructions, is controlled by a third party.
PromiseAn object in JavaScript that acts as a placeholder for an asynchronous task that is yet to be completed. It is the object that is returned from an asynchronous method. When you define a promise object in your script, instead of returning a value immediately, it returns a promise. The promise has three states, which are pending, fulfilled, and rejected.
Pyramid of DoomAnother term for “callback hell”.

References