So what is a promise? A promise represents an asynchronous operation whose result will come in the future.
Before ES6, there was no way to wait for something to perform some operation. For example, when we wanted to make an API call, there was no way to wait until the results came back.
For that, we used to use external libraries like JQuery or Ajax which had their own implementation of promises. But there was no JavaScript implementation of promises.
But then promises were added in ES6 as a native implementation. And now, using promises in ES6, we can make an API call ourselves and wait until it's done to perform some operation.
Я отправлял запро на сервер используя post_url это моя функция которую и я использовал в 2015 году
post.js
function post_url(url, params, function_response)
{
var s = params; // params
var xmlHttpReq = false;
if (window.XMLHttpRequest)
{
// Mozilla/Safari
try
{
xmlHttpReq = new XMLHttpRequest();
}
catch (e) { }
}
else if (window.ActiveXObject)
{
// IE
try
{
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { }
}
}
xmlHttpReq.open('POST', url, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.onreadystatechange = function()
{
// threaded
if (xmlHttpReq.readyState == 4)
{
if (xmlHttpReq.status == 200) // success
{
if (function_response)
function_response(xmlHttpReq.responseText);
}
else
{
// alert('Error: ' + xmlHttpReq.status + ' : ' + xmlHttpReq.statusText);
}
}
}
xmlHttpReq.send(s);
}
Чтобы перерисовать только описание книги и цену я запрашивал html из сервера по book id вот так:
<script language='javascript'>
post_url("$CONFIG_URL_domain/request.php", "GET_BOOK_INFO="+bookId, function (htmlResponse)
{
document.getElementById("div_for_book").innerHTML = htmlResponse;
});
</script>
<script language='javascript'>
$.ajax(
{
type: "POST",
url: "$CONFIG_URL_domain/request.php",
data:{
"GET_BOOK_INFO": bookId
},
complete: function(msg, textStatus)
{
if (textStatus=='error')
alert(msg.status +" " + msg.responseText);
else
{
document.getElementById("div_for_book").innerHTML = htmlResponse;
}
}
});
</script>