What I'm trying to do is run a function after using array.map. Theoretically, I should be able to just run the after the array.map. However, for some reason, it's running the function before array.map is finished. How do I fix this?
Here's my code.
var channelIds = channelNames.map(function (name) {
request(`https://www.googleapis.com/youtube/v3/channels?key=${key}&forUsername=${name}&part=id`, function (error, response, body) {
if (error) {
callback(error);
} else {
var data = JSON.parse(body);
if (data.items.length == 0) {
callback(`Error: No channel id found for ${name}`);
} else {
return data.items[0].id;
}
}
});
});
function test() {
console.log(channelIds);
}
test();
EDIT:
One way which was suggested was to use async.map. For some reason, it doesn't want to run the specified callback function like how the documentation says it should.
Here's how I'm doing it now.
async.map(channelNames, function (name) {
request(`https://www.googleapis.com/youtube/v3/channels?key=${key}&forUsername=${name}&part=id`, function (error, response, body) {
if (error) {
callback(error);
} else {
var data = JSON.parse(body);
if (data.items.length == 0) {
callback(`Error: No channel id found for ${name}`);
} else {
return data.items[0].id;
}
}
});
}, function (error, results) {
console.log(results);
});
Documentation: https://caolan.github.io/async/docs.html#map