I am building a program that takes an excel file as an upload, parses specific text, and then appends that text (or related information) to the body of my html.
One part of my program takes a URL as an input and finds the final URL (the final landing page after redirects). One way I found to do this is to use responseURL property of XMLHttpRequest. This currently takes place inside a for loop. I found that if I tried to append this directly to the console (sans promises), it would appear blank (I believe because ResponseURL is asynchronous and had not finished by the time I tried to append). So I found promises as a potential solution. My problem is that I do not know how to properly implement the promise when it is part of a for loop.
To clarify, I have a list of URLs in an array. I then run through the URLS one at a time, pulling out information (this is where I used responseURL), I then append that information to the body of my HTML, and then move onto the next URL to do the same thing. I've tried various approaches but they all break my program in different ways.
My goal here is to run responseURL asynchronously using a promise and append the result to the html once it is done. Here is the code as I currently have it implemented:
Response URL Function
function finalURLGrabber(ID) {
return new Promise(function(resolve) {
var xhr = new XMLHttpRequest();
xhr.open('GET', ID, true);
xhr.onload = function() {
resolve(xhr.responseURL);
};
xhr.send(null);
});
}
code within the for loop
$('#body').append(Image Source</h2><div class="imageSource content">' + finalURLGrabber(imageSource).then(function(value) {
return value;
}) + '</div></div>');
When I run the function, what appends to the body is '[object Promise]' instead of the final URL.
My questions are as follows:
- Are promises the right thing to use in this situation?
- If they are, how do I implement them properly within a for loop?