Home > Blockchain >  how to perform the function asynchronously? (edited)
how to perform the function asynchronously? (edited)

Time:09-06

UPD: How do I perform the encode function in my code asynchronously? the problem is that encode with a lot of data takes a long time, i would like to encode asynchronously and then add everything to the response array and return to the user

code

var total = records.length
var data = []
var response = []
for(var i = 0; i < total; i  ){
      data.push(records[i])
      response.push([
        records[i].userId,
        global.encode(data)
      ]);
  }

old question ( I was in a hurry and wrote the wrong question ) How to make the array appending asynchronously? The problem is that during an iteration of the array i add new data to it and in the same iteration i need to encode it, with each iteration cycle it takes more and more time question how can i encode and add to the array asynchronously in a synchronous function? here is a code example (not working):

app.post('/encodeSomeData', cors(), (req, res) => {
  var i = 0
  var response = [];
  var records = req.body.data
  var data = []
  async function lol(){
      await encode(i)
      i  ;
      if(i == records.length && response.length == records.length){
        res.send({
          success: true,
          result: response
        })
      }else{
        await lol();
      }
  }

  async function processMyArray (array, index) {
    array[1] = global.encode(array[1])
    response[index] = array
  }

  async function encode(j){
      console.log(j);
      data.push(records[j])
      await processMyArray([
        records[j].userId,
        data
      ], j)
  }
  lol();
});

CodePudding user response:

If your goal is to run multiple Array.push() instances simultaneously, this could work:

async function push(data, array) {
  array.push(data)
}

Appending data is inherently synchronous, but a library like Bacon might be of use

CodePudding user response:

You could just remove the await in the processMyArray function for it to run asynchronously

  • Related