Reputation: 121
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
Reputation: 1074335
You need to:
reuse
out of the forEach
(so you can reuse it)channel
parameter for itforEach
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