2

Why does the following only show me Promise { <pending> }

const Binance = require('binance-api-node').default;
const Client = Binance({
    apiKey: binanceAPIKey,
    apiSecret: binanceAPISecret
});

async function checkBTCAvgPriceLast24h() {
    return await Client.dailyStats({symbol: "BTCEUR"});
}

console.log(checkBTCAvgPriceLast24h());

shouldn't await wait till resolved or rejected?

Uni_x
  • 326
  • 2
  • 14
  • 1
    You need to await on `checkBTCAvgPriceLast24h()`. – user3840170 Apr 10 '21 at 15:33
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – SuperStormer Apr 10 '21 at 15:35

1 Answers1

2

Because an async function itself returns a Promise, and your code is not waiting for it to resolve.

Try chaining your function call with .then() and it should work.

checkBTCAvgPriceLast24h().then(res => console.log(res));

See the code snippet below for better understanding:

const someAsyncTask = () =>
  new Promise((res, rej) => {
    setTimeout(() => {
      res("Here's your data");
    }, 1000);
  });

async function main() {
  return await someAsyncTask();
}

main().then((res) => console.log(res));
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
  • Thanks for your suggestion. Your explanation makes sense but I have tried and still getting `Promise { }` – Uni_x Apr 10 '21 at 15:36
  • Are you sure about the correctness of the code above? – Som Shekhar Mukherjee Apr 10 '21 at 15:38
  • Well I'm a beginner but it should be correct as you can see [here](https://www.npmjs.com/package/binance-api-node#avgPrice). They're doing the same but with `console.log()` on the `dailyStats` method – Uni_x Apr 10 '21 at 15:45
  • Try this: `async function checkBTCAvgPriceLast24h() { console.log(await Client.dailyStats({symbol: "BTCEUR"})) }` and just call the function `checkBTCAvgPriceLast24h()`. See if you get any logs. – Som Shekhar Mukherjee Apr 10 '21 at 15:55
  • well if I run from terminal with `node binance-bot.js` it still only shows `Promise { }` – Uni_x Apr 10 '21 at 15:58
  • 1
    It works for me, I tried it on my system without the keys. Make sure you're doing everything correctly. Copy the code they have on their npm page and try running it, see if that works. – Som Shekhar Mukherjee Apr 10 '21 at 16:06