0

I have an application that populates the array continuously until it is stopped and it does two things:

  • If you click Stop button, it writes values in the DB.
  • Every 1000sec it checks the size of array and if it is > 2000 write the values in the db.

Now I have a problem:

I use the first element of the array to do some calculations, before writing the data to the db.

So if the array exceeds the size of 2000, it performs a splice and passes the array to another page, taking the first element as the basis for the calculation that will be performed on the next page.

At this point, if the user clicks the stop key as the basis for the operations, the last element of the array previously passed must be used.

For example:

array = [0, 20, 40, ......, 2000,..]
array.length > 2000 
arrayBase = 0 // I use it for operations.
// Do a splice
array = [2020, 2040, ...... ]
array.length < 2000
//User click stop Button
//I should pass as arrayBase the last value of array (2000)

I hope at least I have explained myself by example.

This is my code:

//this function populate array until I click stop
populateArray(){
this.arrayTimestamp.push(`${buf.readInt16LE(0)}`);
   this.firstElementTimestamp = this.arrayTimestamp[0];
//.....
}


//This function check the size and write in the DB if > 2000
checkSize(){
that.timeout = setInterval(function() {
    if( (that.arrayTimestamp.length > 2000 ){
      that.arrayTimestampCopy = that.arrayTimestamp.splice( 0, 2000 );
//this is a function in other page where I do some operations
scrittura.write({
counterTimestamp: that.firstElementTimestamp,
//...
})
.then(response => {
//...
})
// I have tried something like this:
that.firstElementTimestamp =  that.arrayTimestamp[2000] //obviously it is undefined as the array with the splice has been emptied

}, 1000);
}


//this is the function when the Stop button is clicked.
stopConnection(){
Actions.Activity({
counterTimestamp: this.firstElementTimestamp,
//...
})
}

So my goal is to find a way to always use the same base in the calculations, without it being updated.

How can I do?

Jack23
  • 1,368
  • 7
  • 32

1 Answers1

0

I think you should use array reduce or Promise All (based on which one you need, parallel or not)

arr.reduce((prom, item) => {
    return prom.then(() => {
        return scrittura.write(item).then((result) => ... );
    });
}, Promise.resolve()).then(function() {
    // all done here
}).catch(function(err) {
    // error here
});

or use Promise All for parallel

You can see another example here Synchronous loop in Promise all

Ahfa
  • 180
  • 8