How do I use a variable outside of an async function?

  • 0
    Good afternoon, please tell me there is such a code.

    const urlChannel = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id=' + channelID + '&fields=items%2Fsnippet%2Fthumbnails&key=' + apiKey;
    
    async function getChannel(){
          const urlChannelResult = await fetch(urlChannel)
          const jsonChannel = await urlChannelResult.json()
          const authorPhoto = jsonChannel.items[0].snippet.thumbnails.high.url;
          console.log(authorPhoto)
        }
        getChannel()


    How can you use the authorPhoto constant outside of a function?
    p.S The code above is inside the map loop, so the channelID changes every time ..
    JavaScript Anonymous, Feb 14, 2019

  • 4 Answers
  • 0
    How can the authorPhoto constant be used outside of a function?


    No way. This constant is in the punctured area. And you can't get access to it.

    But:

    You can return this value from a function (recommended)

    async function getChannel(){
    ...
    return authorPhoto
    }


    Or you can store its value in a variable in a higher scope (not recommended):

    let tempPhoto

    async function getChannel(){
    ...
    tempPhoto = authorPhoto
    }
    Anonymous

  • 0
    The asynchronous function returns a Promise to the main thread. You cannot wait in the main thread for the execution of asynchronous code, so a global variable is not an option, it will be empty until the asynchronous code is executed. In the main thread, you can process the results of asynchronous functions, given that this is a Promise

    https://developer.mozilla.org/en-US / docs / Web / JavaS ...



    It is not clear from your problem where you are going to use this variable, so there is no definite answer to your question.
    Anonymous

  • 0
    async function getChannel(urlChannel){
    const urlChannelResult = await fetch(urlChannel)
    const jsonChannel = await urlChannelResult.json()
    const authorPhoto = jsonChannel.items[0].snippet.thumbnails.high.url
    console.log(authorPhoto
    return authorPhoto
    }
    [...].map(async el => {
    const authorPhoto = await getChannel(el.url)
    // ....
    })
    Anonymous

  • 0
    Use a regular variable instead of a constant. Of course, you will need to be careful not to accidentally overwrite the resulting global variable, but as for me, this is not a problem.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!