JavaScript async



Asynchronous programming


Anynchronous programming makes it possible to run several processes on one processor. Since the processor can only handle one process at a time, the processes are divided tactically and thus the capacity of the processor is used in the best possible way.



The following figure shows the difference between synchron and asynchron.




Callbacks


The principle is to add another instruction to functions that execute a lengthy function after it has finished. In this way, the result can be called after the process has been completed. The example from the unetrreich looked like this:



setTimeout(() => console.log("Tick"), 500);



The function is not executed until 500 ms after termination. This concept makes it possible to run several functions automatically one after the other or to split functions and bridge the waiting times manually by running another function. In this way, callbacks can be used asynchronously.


Promises


An asynchronous action that can be completed at a later time and returns a value is a Promise. It allows communication between different parts of the code by informing anyone who is interested in the results. A Promise can either be created immediately with an existing value or return a value in the future. It is used to move values into an asynchronous reality and perform calculations asynchronously once the values are available. The simplest way to create a Promise is to call Promise.resolve(), which converts the value passed into a Promise. Alternatively, the Promise constructor can be used, which expects a function and calls it immediately to resolve the Promise. Promises are an important concept in asynchronous programming and allow for efficient and well-structured code flows.



The image shows how a Promise is created in the code using a constructor as an example: