Soy un principiante en Javascript/NodeJS y prefiero el trabajo práctico, estoy practicando creando un bot discord con discord.js
El objetivo de este es simplemente mostrarme el valor actual del bitcoin en USD.
Para obtener el valor de BTC, uso el paquete coingecko-api .
Sin embargo, estoy bloqueado porque, aunque puedo obtener el valor de bitcoin, no puedo hacerlo cuando estoy en un bucle sin entender realmente por qué.
principal.js:
var coin = require('./coingecko'); while(true) { coin.btc().then((value => console.log (value) )); // <= This show nothing // Other things ... }coingecko.js:
const CoinGecko = require('coingecko-api'); const CoinGeckoClient = new CoinGecko(); module.exports = { btc: async function btc() { let btc = await CoinGeckoClient.coins.fetch('bitcoin', {}); return btc['data']['market_data']['current_price']['usd']; } }Algun consejo ? Gracias
Ponga su bucle en una función asíncrona. Usar await en lugar de .then() hace que su lógica de bucle sea mucho más sencilla.
const coin = require('./coingecko'); /* declare the async function */ async function doLoop () { while(true) { const value = await coin.btc() console.log(value) // Other things ... } } /* invoke the async function from non-async context */ doLoop().catch(console.error)¿Está seguro acerca de la parte ["data"] ?
Cuando pruebo esta API aquí obtengo esta respuesta: https://www.coingecko.com/en/api/documentation
"market_data": { "current_price": { "aed": 183098, "ars": 5097411, ... "uah": 1356629, "usd": 49850, También probablemente puedas hacer btc.market_data.current_price.usd