1

Ok, I think I am doing the promise wrong. I have 2 problems:

  • The results inside the class is working not problem. but when I retaive it at app.js it is showing as a promise.

  • The results inside the classrooms should be more than one row/object but it is only giving me one result

I am able to get the output I want inside the class, but in the following app.js I get this when I try to retraive the results values : Promise {}

let results
document.getElementById('crypto').addEventListener('keyup', (e) => {
  const cryptoInput = e.target.value;
  console.log(cryptoInput);
  if (cryptoInput.length > 2) {
    results = crypto.getPrice(currency, cryptoInput)
    //here I get Promise {<pending>}
    console.log(results)
  }
})

const table = document.getElementById('resultsTable');
let i = 0;
function showOptions(results) {
  console.log(results)
}

the class is working :

class CoinGecko {
  constructor() {
  }

  async list() {
    const list1 = await fetch(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=1&sparkline=false`);
    
    const list2 = await fetch(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=2&sparkline=false`);
    
    const list1Json = await list1.json();
    const list2Json = await list2.json();
    const list = Object.assign(list1Json, list2Json);
    //const list = list1Json.concat(list2Json);
    return list;
    //console.log(list);
  }
  

  async getPrice(currency = 'usd', crypto) {
    let results=[];
     const toutCrypto = await this.list().then(res => {
      Object.keys(res).forEach(function (element){
      
        if (res[element].id.startsWith(crypto) ||
          res[element].name.startsWith(crypto) ||
          res[element].symbol.startsWith(crypto))
        { 
          //console.log();
          results.push({
            id: res[element].id,
            name: res[element].name,
            image: res[element].image,
            symbol: res[element].symbol,
            price: res[element].current_price,
            date: res[element].last_updated,
          })
          console.log(results[0])
        } 
      });  
     });
    console.log(results[0].id)
    
    return {
        results
        }
  }
}
   
Sara Bi
  • 15
  • 4

1 Answers1

1

sorry for the late answer add await to your async function

results = await crypto.getPrice(currency, cryptoInput)

you are using an async function but not waiting for the response, that's why you get promise as a result

I tested the code, here is an example result: enter image description here

edit: as Phil says, you need to make your event listener async

document.getElementById("crypto").addEventListener("keyup", async (e) => {
Ozan Mudul
  • 750
  • 1
  • 9
  • 20