I'm newer to node.js and writing a program that is going to require promises for async API calls. I have a question regarding the execution of some example code that I have stumbled across in my research.
The code below (from my understanding) will hit an API, wait for the response, then resolve that response as a promise. This is done iteratively and every created promise is passed into an array of promises. Eventually Promise.all() is called on the array of promises and .then() more code will execute to iterate over the array and add the image to the page.
function getMovie(title) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', 'http://mymovieapi.com/?q=' + title);
request.onload = function() {
if (request.status == 200) {
resolve(request.response); // we get the data here, so resolve the Promise
} else {
reject(Error(request.statusText)); // if status is not 200 OK, reject.
}
};
request.onerror = function() {
reject(Error("Error fetching data.")); // error occurred, so reject the Promise
};
request.send(); // send the request
});
}
function fetchMovies() {
var titles = document.getElementById('titles').value.split(',');
var promises = [];
for (var i in titles) {
promises.push(getMovie(titles[i])); // push the Promises to our array
}
Promise.all(promises).then(function(dataArr) {
dataArr.forEach(function(data) {
var img = JSON.parse(data)[0].poster.imdb;
document.getElementById('movies').innerHTML = document.getElementById('movies').innerHTML + '<img src="' + img + '"/>';
});
}).catch(function(err) {
console.log(err);
});
};
fetchMovies();
What I'm not understanding here is how Promise.all() waits for ALL of the API responses to be pushed into promises. Since getMovie(title) resolves every promise before it is pushed into the promises array, shouldn't it be the case that the first resolved promised that is pushed in causes the Promise.all() section to execute (as 1 of 1 promises in the array are resolved)?