在函数中包装一串AJAX请求 - Javascript / JQuery

时间:2017-01-08 15:00:27

标签: javascript jquery ajax

我在forEach()循环中有两个AJAX请求链,第二个依赖于第一个响应。我想重用这段代码,但是当我将它包装在一个函数中时,它就不再有用了。我是Javascript的新手,所以需要我能得到的所有帮助! 下面是代码包装在一个函数之前的代码(它运行正常)......

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

以下是我想在名为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
            });
        });
    };
});

非常感谢提前

1 个答案:

答案 0 :(得分:4)

你需要:

  1. reuse移出forEach(以便您可以重复使用)
  2. 为其声明channel参数
  3. 将其传递到forEach
  4. 像这样:

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

    附注:功能声明后面不需要;;是一个语句终止符。 (但这无害。)