Home > OS >  Asynchrounus updating array
Asynchrounus updating array

Time:05-02

is it possible to update an java script array asyncronously? It should look like this:

export const main = async () => {
    let array = []
    const update = async() => {
       //this should update the array every "interval"-seconds              
    }
    update();
    setInterval(update, interval);
    const usage = async() => {
       //this uses the array every n-seconds             
    }
    usage();
    setInterval(usage, n);

CodePudding user response:

Move the update() and usage() functions outside your main() function like this:

const update = async(array) => {
    array.push("newValue") 
}

const usage = async(array) => {
   return array            
}

export const main = async () => {
    let array = []
    const upd_interval = 10;
    const use_interval = 20
    setInterval(await update(array), upd_interval);
    setInterval(await usage(array, use_interval);
}

CodePudding user response:

//calling this function will get your most recent array value
// it does not have to be asynchronous, as it just returns the array. Adding async would therefore be pointless.
const usage = (array) => return array

export const main = async () => {
  let array = []
  //this should update the array every "interval"-seconds  
   const update = async(array) => {
      const updated_arr = array
      //perform async updating logic
      array = updated_arr            
   }
  setInterval(update, interval);
}
  • Related