0

i've a code like this:

var express = require('express');
var router = express.Router();
const Binance = require('node-binance-api');
const binance = new Binance().options({
    APIKEY: 'APIKEY',
    APISECRET: 'APISECRET',
    useServerTime: true
});
r = [];

binance.balance((error, balances) => {
    if ( error ) return console.error(error);
    r = balances;
});

router.get('/', function(req, res, next) {
    res.render("index", {page: 'home', user: req.thisUser, balances: r});
});

module.exports = router;

How can i get and pass the balances to get request in params? The result take long time to return.

Thank you all.

Simon D.
  • 30
  • 5
  • Could you give just a little more detail into what your issue is? Like, is the page you are viewing not displaying the balances data? Or is it that it is just slow? Because it could be an async-await problem that you are facing – MTN Apr 10 '20 at 00:39

1 Answers1

1

So I haven't tested this code, I've never used this Binance API wrapper before but I would imagine this should work/is what you're asking.

I've wrapped that call in a promise so that when you hit the route it will wait until the call to Binance completes, and it will return with either the error if there is one or your balances, illustrated in the documentation for node-binance-api like below:

{ BTC: { available: '0.77206464', onOrder: '0.00177975' },
  LTC: { available: '0.00000000', onOrder: '0.00000000' },
  ETH: { available: '1.14109900', onOrder: '0.00000000' },
  BNC: { available: '0.00000000', onOrder: '0.00000000' } }
const express = require('express')
const Binance = require('node-binance-api')

const router = express.Router()

const binance = new Binance().options({
    APIKEY: 'APIKEY',
    APISECRET: 'APISECRET',
    useServerTime: true,
})

const getBalances = () => {
    return new Promise((resolve, reject) => {
        binance.balance((error, balances) => {
            if (error) return reject(error)
            return resolve(balances)
        })
    })
}

router.get('/', async (req, res) => {
    const balances = await getBalances()
    res.render('index', { page: 'home', user: req.thisUser, balances })
})

module.exports = router
razki
  • 1,171
  • 2
  • 8
  • 16