我在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
});
});
};
});
非常感谢提前
答案 0 :(得分:4)
你需要:
reuse
移出forEach
(以便您可以重复使用)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);
附注:功能声明后面不需要;
。 ;
是一个语句终止符。 (但这无害。)