Simon D.
Simon D.

Reputation: 30

NodeJS variable scope, functions and callbacks

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.

Upvotes: 0

Views: 108

Answers (1)

razki
razki

Reputation: 1229

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

Upvotes: 1

Related Questions