Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Promises Loop

So I followed the course material and it works as intended but I have a use case where I might have to loop the Promise

function getJSON(url) {
    return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.onreadystatechange = handleResponse;
        xhr.onerror = function(error) { reject(error); }
        xhr.send();

        function handleResponse(){
            if(xhr.readyState === 4){
                if( xhr.status === 200){
                    var results = JSON.parse(xrh.responseText);
                    resolve(results);
                } else {
                    reject(this.statusText);
                }
            }
        };
    });
}

ajaxPromise = getJSON('http://url_a')
.then(getJSON(http://url_b))
.then(doSomethingWithBothResponses);

for example...

I need to run a ajax request to got query a table for its column names get that info and then query another table for its column names and add both responses to an array called column names.

1 Answer

If you don't need the response from the from your first query to make your second you can use Promise.all() to make both simultaneously. Then you'd have the data from both:

Promise.all( [getJSON('http://url_a'), getJSON('http://url_b')] )
    .then(doSomethingWithBothResponses);    // the function is passed an array of both results

NOICE!

basically, I have a UI that allows the user to make new fields but names of columns on tables in the database are banned. I could hard code.... BUT for reusability it seems like I should run a query getting the columns on the tables in question, store them in an array and check the user's named fields against that.

Thanks for the help.