-1

I am using Binance's Node.js API. It says regarding "Get open orders for a symbol", I should do:

binance.openOrders("ETHBTC", (error, openOrders, symbol) => {
  console.info("openOrders("+symbol+")", openOrders);
});

To print out number of open orders, I do:

binance.openOrders("ETHBTC", (error, openOrders, symbol) => {
  console.info(openOrders.length);
});

which works and the number gets printed out. However, I would need this result to be stored in a variable which can be used later by other functions. Building on SO's Javascript chat room, I do:

let OO =
(async() => {
  const openOrders = await binance.openOrders(false);
  return openOrders.length
})()
console.log(OO)

This however prints

Promise { <pending> }

only.

I have seen several other questions discussing Promise { <pending> } issue but I haven't been able to implement their solutions to this specific case.

How could I get number of open orders into a variable accessible by other functions?

zabop
  • 6,750
  • 3
  • 39
  • 84

1 Answers1

1

You'll need to use either completely async approach or use callbacks.

The last block in your question shows exactly what this answer explains. Javascript doesn't wait for Promise to resolve/reject in a synchronous context. So your "async" block returned the unresolved Promise and the rest of your (synchronous) code didn't wait for it to resolve.

Example of using async functions

const getOpenOrdersCount = async () => {
    const openOrders = await binance.openOrders("ETHBTC");
    return openOrders.length;
};

const run = async () => {
    const openOrdersCount = await getOpenOrdersCount();
    console.log(openOrdersCount);
}

Note: You can use await only within async functions.

Example of using callbacks is your code. They are useful in a small scope, but in bigger scope they get messy and turn into a callback hell. So I wouldn't recommend using callbacks in a bigger scope.

binance.openOrders("ETHBTC", (error, openOrders, symbol) => {
  console.info(openOrders.length);

  // here goes rest of your code that needs to use the `openOrders` variable
});
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100