total_arr={}
total=0
data={"a":1,"b":2,"c":3}
const Binance = require('node-binance-api');
const binance = new Binance().options({
APIKEY: '<key>',
APISECRET: '<secret>'
});
async function trigger(){
async function trig() {
for (keys in data){
var x= await binance.futuresMarketBuy( 'BNBUSDT', data[keys] )
var x2= await binance.futuresMarketBuy( 'BTCUSDT', x )
total_arr["buy"+keys]=x+x2;
}
}
async function trig2() {
var y =await binance.futuresMarketSell( 'BNBUSDT', data[keys] )
var y2= await binance.futuresMarketSell( 'BTCUSDT', y )
total_arr["sell"+keys]=y;
}
async function trigger(){
for (keys in data){
await trig(); /*I want to run trig() and trig2() asynchronously */
await trig2();
}
for (iterat in data) await {
total=total+data[iterat] /*AFTER trig() and trig2() have COMPLETELY run in for loop, I want
to add them up this way*/
}
console.log(total)
}
}
trigger();
我想异步运行trig()和trig2(),尽管使用了async / await,但它仍然按顺序运行。我究竟做错了什么 ? 。请帮忙。我已经尝试了很多次代码,但仍然可以按顺序运行。请帮忙。
答案 0 :(得分:0)
请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all。
await Promise.all([trig(), trig2()])
很难确定您要做什么,但是我认为这更加接近:
const Binance = require('node-binance-api');
const total_arr = {};
let total = 0;
const data = {"a" : 1, "b" : 2, "c" : 3};
const binance =
new Binance().options({APIKEY : '<key>', APISECRET : '<secret>'});
async function buy() {
for (const key in data) {
var x = await binance.futuresMarketBuy('BNBUSDT', data[key]);
var x2 = await binance.futuresMarketBuy('BTCUSDT', x);
total_arr["buy" + key] = x + x2;
}
}
async function sell() {
for (const key in data) {
var y = await binance.futuresMarketSell('BNBUSDT', data[key]);
var y2 = await binance.futuresMarketSell('BTCUSDT', y);
total_arr["sell" + key] = y;
}
}
async function main() {
await Promise.all([ buy(), sell() ]);
for (const key in data) {
total = total + data[key];
}
console.log(total);
}
main();