My current understanding of promises is that they serve as a wrapper for async functions within the outer environment (such as the browser or node.js). However, I am struggling with how to properly connect async operations using promises in software development. Here is the issue I've encountered:
In the code snippet below, a setTimeout
function is wrapped in a promise, along with an XMLHttpRequest
call. Initially, I assumed that chaining them together would result in the timer running first and then followed by the AJAX call. However, this wasn't the case as the AJAX call executed before the timer.
timer(1000).then(AJAXGetRequest('https://itunes.apple.com/hk/rss/topalbums/limit=10/json'))
I found that rewriting my promise chain like the following produced the expected results:
timer(1000).then(function(){
AJAXGetRequest('https://itunes.apple.com/hk/rss/topalbums/limit=10/json')
})
The drawback of the above code is that it resorts back to using callbacks for async operations. I believe there must be a way to structure my code without reverting back to callbacks, possibly something like this:
timer(1000)
.then(AJAXGetRequest('some/api'))
.then(timer) // wait
.then(AJAXGetRequest('someOther/api'))
.then(timer) // wait
.then(AJAXGetRequest('another/api'))
// wait
Or perhaps even more flexible:
timer(1000)
.then(AJAXGetRequest('some/api'))
.then(timer(200)) // wait
.then(AJAXGetRequest('someOther/api'))
.then(timer(600)) // wait
.then(AJAXGetRequest('another/api'))
// wait
Below you'll find the remaining code related to the examples mentioned above:
let timer = function(value) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(value);
resolve(value);
}, value);
});
};
let AJAXGetRequest = function(URL) {
return new Promise((resolve, reject) => {
var getRequest = new XMLHttpRequest();
getRequest.open('get', URL, true);
getRequest.send();
getRequest.onload = function() {
var JSONObject = JSON.parse(getRequest.responseText);
console.log(JSONObject);
resolve(JSONObject); // object
}
});
};