0

I have this part of code:

client.on("messageCreate", msg => {
    if (msg.content.toLowerCase().startsWith('-p')) {
        msg.content = msg.content.slice(3);
        enlace = google.youtube('v3').search.list({
            key: process.env.YOUTUBE_TOKEN,
            part: 'id',
            q: msg.content,
            maxResults: 1
        }).then((response) => {
            const { data } = response;
            data.items.forEach((item) => {
                const link = item.id.videoId;
                console.log(link)
                console.log(typeof (link))
                return link
            })
        }).catch((err) => console.log(err));
        console.log(enlace)
    }
})

What i pretend it to do, is to get the data from the variable "link" and use it outside the .then(), then i would do something else with that data The problem is that, in the log i get this:

ACA EMPIEZA EL LOG
Poe esta online
Promise { <pending> }
YVkUvmDQ3HY
string

It seems the line console.log(enlace) executes before the other to logs and without the value i expect. How can i get the execution to wait for the data to be already stored in the variable enlace before logging it and how to actually store the value of link into enlace

  • Is `enlace` supposed to be an array of `link`'s? if so then you should use map instead of forEach and return the array. you would also need to `await` or chain another `then` to wait for the promise to resolve before console.log – Matt Aft Sep 27 '21 at 18:43
  • BTW you don't need all this `.catch((err) => console.log(err));`, simply `.catch(console.log)` will do. But you might even want [`console.error`](https://developer.mozilla.org/en-US/docs/Web/API/console/error). – msanford Sep 27 '21 at 18:43

0 Answers0