0

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
  • Perhaps you should research (just google) what promises are, how to use them, and what async/await has to do with promises. Do that, and you'll know why you get `Promise {}`. (Hint: the promise is *pending*... could it mean it's not ready yet?) – code Feb 21 '22 at 20:07

1 Answers1

-1

If 'results' in a promise then it won't execute until you trigger it by telling it how to resolve. To do this, you call Promise.prototype.then((resp) => {...})

Alternatively, you can declare your arrow functions and make them async and use await, but I would suggest that since you're new to Promises you do them the simple way and become accustomed to them. Once you understand how they work, you can use them with async/await, but since that is less intuitive you can stick to the basics.

crypto.getPrice(currency, cryptoInput)
  .then(data => results = data)
  .catch(err => console.error(err)); 
// simplified Promise chaining with catch method.
msenne
  • 613
  • 5
  • 8
  • 1
    the `.then(data => results = data)` line incorrectly insinuates that you can update an outside variable with the data from the promise. – Kevin B Feb 21 '22 at 19:42
  • Please clarify, @KevinB, are you saying that class member variables cannot be modified from within callbacks in JavaScript? Maybe there's a miscommunication here because I do it all the time. – msenne Feb 21 '22 at 19:47
  • They can be, however, it's generally a useless practice to update a variable from within a promise as you still need to use the promise to access it safely. Unless, of course, you're updating a react or angular state which deals with the asynchronous nature of promises in it's own way. – Kevin B Feb 21 '22 at 19:49
  • In the OP's scenario, the only situation where the result variable *could* contain the data would be if the function was async and they used await. using .then instead as you are doing, they'd need to work with `result` within that callback where you set result to data, or within a subsequent .then off of the same chain. Even though technically the same result var is holding the data, it's useless outside of the .then because all of that logic occurred before the .then callback. – Kevin B Feb 21 '22 at 19:54
  • it didnt work . I feel I am making it way more complecated. – Sara Bi Feb 21 '22 at 20:32
  • Can you explain what didn't work? You can use console log statements to determine if the suggested code is ever executed and whether the values were obtained. If you can clarify whether the Promise is being resolved at all, or whether the problem is with accessing the data from the Promise resolution that would help. – msenne Feb 21 '22 at 20:50