How do I pass a value to an external variable?

  • 0
    Hello. Why, in this code, alert outside .then () outputs undefined value, although the variable itself is declared outside this construction.
    <meta charset="utf-8">
    <script type="text/javascript">
        var USD
        fetch('https://www.cbr-xml-daily.ru/daily_json.js')
            .then(data => data.json(data))
            .then(({
                Valute: {
                    USD
                }
            }) => {
    
                USD = `${USD.Value}`
                alert(USD)
            })
        alert(USD)
    
    </script>

    I will need to work with this variable further in the code. I don't know JS well. I couldn't find the answer in Google
    JavaScript Anonymous, Apr 14, 2019

  • 1 Answers
  • 0
    Because this is how asynchronous operations work. Use async / await for convenience.
    Phoebe Vincent

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