It has, rightfully, become the standard for dynamic content on the web. Browsers would be crazy not to support it, and websites are nothing without it.
The way it works is brilliant. In an HTML page, open a
<script> tag et voila! You have the power to create scripts within your browser!
<head> <title>My amazing website</title> <script> var a = 5 var b = a * 2 alert(b) </script> </head>
And it works just like any other language, like Java or Python, works! Starting from the top, it would execute the script line by line until it reaches the bottom. And it all happens in the browser whenever your user loads the page. Brilliant stuff!
The code block above does some pretty basic stuff. It assigns a variable, does some maths to it and then shows a popup alert with the result. It should take milliseconds to run, which means that the user doesn't even realise it happened.
Imagine we do something similar in Python. We want to ask for some data from another website, store it in a variable and we display it to the user:
data = get_data_from("https://api.example.com/data") print(data)
If we were to run this in a terminal, we would expect it to freeze for a few seconds until the data is given to us and then print that data to the terminal. This is expected behaviour which is OK when it happens in the terminal.
var data = getDataFrom("https://api.example.com/data") console.log(data)
Users would click on buttons expecting something to happen and nothing would. This is awful user experience! Something needed to be done to fix this problem!
Promises are the solution to the data request problem. It is essentially a way of saying:
"Go get some data from this API. However, I'm not gonna sit here and wait for you because that could take a while and it would freeze my browser"
Promises are also a way of saying:
"Go get some data from this API. I'm going to move on to the next line, BUT once you've got some data back, I want you to do SOMETHING with them".
See this example below:
If we run the example above this is what will happen:
- Print "Getting some data for you..."
- Request some data
- Once the data is back, print the data and then print "All done!"
This was based on this Twitter thread posted a month ago and proven quite popular