Olly B
Olly B

Reputation: 121

Wrapping a chain of AJAX requests within a function - Javascript/JQuery

I have a chain of two AJAX requests within a forEach() loop, the second relying on the firsts response. I want to reuse this block of code, but when I wrap it within a function it no longer works. I'm new to Javascript so need all the help I can get! Below is the code before it's wrapped in a function (it works fine)...

channels.forEach(function (channel) {
    $.getJSON("URL" + channel)
    .then(function (data) {
        if (data.stream !== null) {
            return "stuff";
        }
        else {
            return "other stuff";
        }
    })
    .then(function (returnedStuff) {
        $.getJSON("OtherURL" + channel)
        .done(function loadData(data) {
            //...Append data to DOM
        });
    });
});

And below is the section of code I want to reuse inside a function named reuse...

channels.forEach(function (channel) {
    function reuse() {
        $.getJSON("URL" + channel)
        .then(function (data) {
            if (data.stream !== null) {
                return "stuff";
            }
            else {
                return "other stuff";
            }
        })
        .then(function (returnedStuff) {
            $.getJSON("OtherURL" + channel)
            .done(function loadData(data) {
                //...Append data to DOM
            });
        });
    };
});

Many thanks in advance

Upvotes: 4

Views: 221

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

You need to:

  1. Move reuse out of the forEach (so you can reuse it)
  2. Declare a channel parameter for it
  3. Pass it into the forEach

Like this:

function reuse(channel) {
    $.getJSON("URL" + channel)
        .then(function(data) {
            if (data.stream !== null) {
                return "stuff";
            }
            else {
                return "other stuff";
            }
        })
        .then(function(returnedStuff) {
            $.getJSON("OtherURL" + channel)
                .done(function loadData(data) {
                    //...Append data to DOM
                });
        });
}
channels.forEach(reuse);

Side note: Function declarations don't need ; after them. ; is a statement terminator. (But it's harmless.)

Upvotes: 4

Related Questions