-1

I store a value locally like this:

await GM.setValue("current_page_url", current_page_url);

Then I loop through an object via .each() and after a timeout, attempt to get the value:

$j_object.each( function(){
    
    setTimeout(function() {
        var getting_page = await GM.getValue('current_page_url');
        alert(getting_page);
    }, 4000)

});

But it returns undefined. I believe this is because of how I'm using await inside the loop and setTimeout(), but not sure.

What's the correct approach?

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

1 Answers1

1

There are a few considerations:

  1. As mentioned by Jaromanda X, await goes with async
  2. 'current_page_url' seems to be fixed so why would the script need to get it and run an asynchronous function on every loop reiteration?
  3. What is the aim of setTimeout in a loop? It will run rapidly after the initial time-out i.e.
    • Loop 1: wait and run after 4 sec
    • Loop 2: faction of a millisecond later, wait and run after 4 sec
    • Loop 3: faction of a millisecond later, wait and run after 4 sec
    • etc

In practice, after 4 seconds, loop 1, 2, 3, etc will run one after the other.

Here is an example ...

(async() => {

// wait to be set the value
await GM.setValue("current_page_url", current_page_url);

/* some code */

// wait to be get the value
const getting_page = await GM.getValue('current_page_url');

$j_object.forEach(function(){
    
    setTimeout(function() {
        console.log(getting_page);
    }, 4000)
});

})();

If you really need to run the asynchronous GM.getValue() in a loop. you can also use then() e.g.

(async() => {

// wait to be set the value
await GM.setValue("current_page_url", current_page_url);

$j_object.forEach(function(){
    
    setTimeout(function() {
      GM.getValue('current_page_url').then(getting_page => console.log(getting_page));
    }, 4000)
});

})();

If you want to delay each reiteration by 4 seconds (e.g. so 5 reiteration takes 20 seconds), then you can check the answer in Combination of async function + await + setTimeout.

erosman
  • 7,094
  • 7
  • 27
  • 46