Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - Get number of open orders for a symbol using Binance's Node.js API

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...