Promise , object literal , API java 脚本

Promise , object literal , API java Script

好吧,我想我做错了承诺。我有 2 个问题:

我能够在 class 中获得我想要的输出,但是在下面的 app.js 中,当我尝试返回结果值时我得到了这个: 承诺{}

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)
}

class 正在工作:

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
        }
  }
}
   

抱歉回答晚了 将等待添加到您的异步函数

results = await crypto.getPrice(currency, cryptoInput)

您正在使用异步函数但没有等待响应,这就是您得到 promise 结果的原因

我测试了代码,这是一个示例结果:

编辑:如 Phil 所说,您需要使事件侦听器异步

document.getElementById("crypto").addEventListener("keyup", async (e) => {