2

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

Bootsie123
  • 161
  • 1
  • 13
  • 2
    The built-in `.map()` method is not designed to support asynchronous operations. It won't wait for the `request()` to complete. – Related: [Is map() in javascript synchronous?](https://stackoverflow.com/questions/24629629/is-map-in-javascript-synchronous) and [Use async await with Array.map](https://stackoverflow.com/questions/40140149/use-async-await-with-array-map/40140359). – Notable alternative: [`async.map()`](https://caolan.github.io/async/docs.html#map) – Jonathan Lonowski Mar 11 '18 at 22:49
  • ah. I guess I had it wrong then. Thank you! – Bootsie123 Mar 11 '18 at 22:52
  • I tried using `async.map()`. For some reason now it's not running the callback function. – Bootsie123 Mar 11 '18 at 23:07

1 Answers1

6

How about using Promise.all to resolve all async functions before you call test method?

Try this :

const promiseArray = channelNames.map(function (name) {
        return new Promise(function (resolve, reject) {
          request(`https://www.googleapis.com/youtube/v3/channels?key=${key}&forUsername=${name}&part=id`, function (error, response, body) {
            if (error) {
                callback(error); return reject(error);
            } else {
                var data = JSON.parse(body);

                if (data.items.length == 0) {
                    callback(`Error: No channel id found for ${name}`);
                    return reject(`Error: No channel id found for ${name}`);
                } else {
                    return resolve(data.items[0].id);
                }
            }
        });    

  });
});

Promise.all(promiseArray).then(function(channelIds) {
  console.log(channelIds);
})
binariedMe
  • 4,309
  • 1
  • 18
  • 34
  • Thanks! It worked! I tried looking into promises before, however, I was pretty confused on how to implement it. Thank you! – Bootsie123 Mar 11 '18 at 23:35
  • @Bootsie123 however you should remove the line where you are calling "callback" as I don't see what is callback and probably you mistook it while copying... – binariedMe Mar 11 '18 at 23:36
  • There was a bit of code which I didn't show. All of this code is in a separate file from my main code which handles the errors. In that main file when it runs this file it gives it a function which is named callback. Callback is ran if there is an error or once the file has finished running. – Bootsie123 Mar 11 '18 at 23:40
  • oh, you are fine then... My mistake – binariedMe Mar 11 '18 at 23:41
  • No worries. Thanks for the help! – Bootsie123 Mar 11 '18 at 23:42