I am new to JS and was learning promises and how they are used in JS and I would like to ask some questions. Firstly, if you look at the code below:
var makeRequest = function (url, method) {
// Create the XHR request
var request = new XMLHttpRequest();
// Return it as a Promise
return new Promise(function (resolve, reject) {
// Setup our listener to process compeleted requests
request.onreadystatechange = function () {
// Only run if the request is complete
if (request.readyState !== 4) return;
// Process the response
if (request.status >= 200 && request.status < 300) {
// If successful
resolve(request);
} else {
// If failed
reject({
status: request.status,
statusText: request.statusText
});
}
};
// Setup our HTTP request
request.open(method || 'GET', url, true);
// Send the request
request.send();
});
};
makeRequest('https://some-url.com/posts')
.then(function (posts) {
console.log('Success!', posts);
})
.catch(function (error) {
console.log('Something went wrong', error);
});
The first question I would like to ask is about callback of then(), I mean the callback that we use inside then() like then((data)=>{console.log(data)}). Can I imagine it as asynchronous callback that we used before promises, that is, the callback that awaited until asynchronous, for example, xhr object finishes and returns result. And, in promise the callback of then() waits until promise gives result which MEANS PROMISE HELPS TO DECOUPLE CALLBACK FUNCTION FROM ASYNCHRONOUS OPERATION. The second question, is the callback of then() asynchronous, I mean, is it also run via event loop as well as asynchronous code that promise wraps or the code, that promise wraps e.g xhr object, are the only asynchrony in promises? The third question, when we say function returns promise, does it mean that promise is returned right away regardless of whether it was resolved or not. Can I imagine it like this when function returns promise, that returned promise kinda tells us "please wait a bit and I promise I will provide you with the result which you can handle with then()"