使用Binance的Node.js API获取交易品种的未结订单数量 [英] Get number of open orders for a symbol using Binance's Node.js API
问题描述
我正在使用Binance的 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);
});
有效,并打印出数字.但是,我需要将此结果存储在一个变量中,以后可以由其他函数使用.我建立在 SO的Java聊天室上,
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)
但这会打印
Promise { <pending> }
仅.
我还看到了其他几个讨论 Promise {< pending>}
问题,但我无法针对此特定情况实施他们的解决方案.
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?
推荐答案
您将需要使用完全异步的方法或使用回调.
You'll need to use either completely async approach or use callbacks.
问题中的最后一个方框准确地显示了此答案所解释的内容.Javascript不等待 Promise
在同步上下文中解析/拒绝.因此,您的异步"块返回了未解决的 Promise
,并且您的其余(同步)代码没有等待其解决.
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.
使用异步函数的示例
const getOpenOrdersCount = async () => {
const openOrders = await binance.openOrders("ETHBTC");
return openOrders.length;
};
const run = async () => {
const openOrdersCount = await getOpenOrdersCount();
console.log(openOrdersCount);
}
注意:您只能在 async
函数中使用 await
.
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
});
这篇关于使用Binance的Node.js API获取交易品种的未结订单数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!