I'm a beginner in Javascript/NodeJS and I'm prefer practical work, I'm practicing by creating a bot discord with discord.js
The objective of this one is simply to display me the current value of the bitcoin in USD.
To get the value of BTC, I use the coingecko-api package.
However I'm blocked because although I can get the value of bitcoin, I can't do it when I'm in a loop without really understanding why.
main.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'];
}
}
Any tips ? Thank's
CodePudding user response:
Put your loop into an async function. Using await
rather than .then()
makes your looping logic much more straightforward.
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)
CodePudding user response:
Are you sure about the ["data"]
part?
When I test this API here I get this response: https://www.coingecko.com/en/api/documentation
"market_data": {
"current_price": {
"aed": 183098,
"ars": 5097411,
...
"uah": 1356629,
"usd": 49850,
Also you can probably just do btc.market_data.current_price.usd