GET IN SYNC WITH ASYNC JS!!
The process of developing a full-fledged Web-app might seem a bit daunting. It requires a lot of concentrated developers' hours. One of the Key aspects of developing a full stack web app is fetching data. As a full-stack developer, data fetching becomes an integral part of the profession, and mastering the art of handling that information is what one must strive to achieve.
Function A - (slowFunction) generates data in a non-predefined amount of time.
Function B - (dataProcessor) responsible for utilising said data.
Function A is called. Due to the asynchronous behavior of JS, function B is executed before function A is able to generate its result. Function B gets ‘null/undefined’ as input, leading to errors.
A callback is a function passed as an argument to another function. The code is set up in such a manner that the passed function will execute only after the main function is done with its own processing.
Solving the above problem, function A will be passed another argument, a callback, during its initialization. That callback is passed the fetched data. When Function A is called, the callback is replaced by function B (responsible for utilising the data).This way, function B will wait for function A to complete its execution.
To make this code real-world ready, we can add separate callbacks for both success and failure cases because let's be real, there is no way your backend is that good :)
A promise is an object that gives us either a result of an asynchronous operation or an error to that asynchronous operation. Promises are initiated as ‘new Promise’ with two variables (resolve, reject). The promise is consumed with '.then' and '.catch' functions responsible for success or failure respectively.
For the problem, a new promise is returned inside function A. A positive result is returned using the resolved variable whereas a negative result is returned using the reject variable. When the function is called, it’s followed by the above mentioned ‘.then’ and ‘.catch’ functions to handle both success and failure.
When a function is provided with the async designation, it automatically returns a promise, allowing the user to consume the function’s response with ‘.then’ and ‘.catch’.
For the problem, the logic inside function A is wrapped by a promise. Function A is called inside a different async function. The return from function A is stored in a variable which would be used by function B for further processing. Now, for function A to complete its processing, we need to stop the code execution before function B consumes the data. Declaring the ‘process’ function (see image) an async function and adding ‘await’ before function A, we can wait for function A to return the data and then pass it onto function B.
If you have any questions, ping me on twitter @dabibu1.