Search code examples
javascriptasynchronousasync-awaitpromisereturn

return a value out of an eventListener that is inside of a forof loop


How can I pass the returned coin object from the displayCurrencies function to the getCoinId function to use it as a parameter in the API call for retrieving the specific coin data?

this is the function i created to return the value:

let returnID = (value) => {
  return value;
};

this is the function that i want to return coin from:

let displayCurrencies = async () => {
  let coinsContainer = document.querySelector(`.coins`);
  try {
    let coins = await getData();
    let coinsArray = [];
    let coinElement;
    for (const coin of coins) {
      coinElement = coin;

      if (coinsArray.length > 20) {
        break;
      }
      coinsArray.push(coin);
      // create Nodes
      let coinDisplay = createElement(`li`, `coin`);
      let coinSymbolElement = createElement(`p`, `coinSymbol`);
      let coinIDElement = createElement(`p`, `coinID`);
      // set Values
      coinSymbolElement.innerHTML = coin.symbol;
      coinIDElement.innerHTML = coin.id;

      // append
      coinDisplay.append(coinSymbolElement, coinIDElement);
      coinsContainer.appendChild(coinDisplay);

      coinDisplay.addEventListener(`click`, () => {
        openModal();
        returnID(coin);
      });
    }
    let returnCoin = returnID
    coinDisplay.addEventListener(`click`, () => {
    console.log(returnCoin);
    });

    console.log(returnCoin);
    
  } catch (error) {
    console.log(error);
  }
};

and last, this is the function that i want to use the returned value at:

displayCurrencies();
let getCoinId = async () => {
  let coinID = await displayCurrencies();
  let currencyData = `https://api.coingecko.com/api/v3/coins/${coinID}`;
  let responseData = await fetch(currencyData);
  let dataOfCoins = await responseData.json();
  console.log(dataOfCoins);
};

Solution

  • You can simply add an onclick event for each element, and when the call-back is called you invoke the getCoinID function passing the coinID as a parameter.

    A simple example:

    <ul class="coins">
    </ul>
    
    <script>
        function addOnClick() {
            let coinsContainer = document.querySelector('.coins');
            let coins = [
                { id: 1, symbol: 'bitcoin' },
                { id: 3, symbol: 'brazil-fan-token' },
                { id: 4, symbol: 'celo-euro' },
            ]
    
            for (const coin of coins) {
                let coinDisplay = document.createElement('li')
                let coinSymbolElement = document.createElement('p')
                let coinIDElement = document.createElement('p')
    
                coinSymbolElement.innerHTML = coin.symbol
                coinIDElement.innerHTML = coin.id
    
                coinDisplay.appendChild(coinIDElement)
                coinDisplay.appendChild(coinSymbolElement)
    
                coinsContainer.appendChild(coinDisplay)
    
                coinDisplay.addEventListener('click', () => {
                    getCoinID(coin.symbol)
                })
            }
        }
    
        async function getCoinID(coinID) {
            let currencyData = `https://api.coingecko.com/api/v3/coins/${coinID}`
            let responseData = await fetch(currencyData)
            let dataOfCoins = await responseData.json()
            console.log(dataOfCoins)
        }
    
        addOnClick()
    </script>