简体   繁体   中英

async/await in for loop javascript.

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

I want to run trig() and trig2() asynchronously but it still runs sequentially despite using async/await. What am I doing wrong ? . Please help. I have experimented with code many times but it still runs sequentially. Please Help.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all .

await Promise.all([trig(), trig2()])

It's hard to tell for certain what you're trying to do, but I think this is closer:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM