binance-exchange / node-binance-api

Node Binance API is an asynchronous node.js library for the Binance API designed to be easy to use.
MIT License
528 stars 145 forks source link

Problem with await when getting balances #215

Closed Miguel349 closed 3 years ago

Miguel349 commented 3 years ago

Hi,

Node.js newbie here. I have found the library very useful up to now but have an issue with getting the balances.

What I want is to be able to wait for the balances of my user to get loaded before continuing with the logic of my application, however the binance.balances function is not structured in the same way as the others and completely ignores my calls to await:

await binance.useServerTime(); // @ts-ignore let test=await binance.balance(async (error, balances) => { const assets={}; if (error){ console.error(error); return null; } for (const [key, value] of Object.entries(balances)) { // @ts-ignore if(value.available>0 || value.onOrder>0){ console.log(key); console.log(value); // @ts-ignore assets[key]={available:value.available,onOrder:value.onOrder}; } } //Prints assets after test console.log("ASSETS IS: " + assets);

    console.log("FINISHED EXECUTING, TEST IS: ");
    //Test is null 
console.log(test);
return test;

When i log test it is of course undefined 
Is there any way you can maybe I can wrap this up in a promise or something that I'm not seeing so that it behaves in a syncronous manner? If there's no way I can do it, could you wrap it up on the api so it follows the same logic as the other functions? 

Thanks in advance. 

Also, is there any way of importing the project for typescript? I keep having to supress all the calls to the API since I don't have a structure (Very noobie question.. But still). 
StevenJ59 commented 3 years ago

hello, for use await you have to use async

(async () => { const Binance = require('node-binance-api'); const binance = new Binance().options({ APIKEY: '123', APISECRET: '456' });

let testtime= await binance.useServerTime(); console.info(testtime)

})();

Miguel349 commented 3 years ago

Hi @StevenJ59,

Unfortunatelly it's not in the initialization, it is in the binance.balance function. This function I'm guessing works with a stream so therefore it is returning inmediatelly and no matter how much I wrap it up, it does not wait, which is annoying because I need the balance data of my account to be able to continue. It works correctly, simply executes when it wants, and I need to have the info syncronously so I can then query the different markets according to the balances I have.

Any other idea/solution that I'm not thinking of?

Miguel349 commented 3 years ago

Solved, it was already defined, but I got mixed with up with the documentations, all I had to do was: let balances=await binance.balance();

instead of: binance.balance(async (error, balances) => {

Because the second method gives back the stream and it's imposible to await.

Thanks anyway @StevenJ59