Wrapping an AJAX request chain inside a function - Javascript / JQuery

I have a chain of two AJAX requests in a forEach () loop, the second based on the first answer. I want to reuse this block of code, but when I wrap it inside a function, it no longer works. I'm new to Javascript, so I need all the help I can get! Below is the code before ending it 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 a code snippet that I want to reuse inside a function called 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
            });
        });
    };
});

Thank you very much in advance

+4
source share
1 answer

You need:

  • Move reusefrom forEach(so you can reuse it)
  • channel
  • forEach

:

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);

: ;. ; . ( .)

+4

Source: https://habr.com/ru/post/1666152/


All Articles