-1

I tried updating IndexedDB data inside ".then" in fetch but that doesn't work inside event handlers as I got to know that from this post post-link. Updating the IndexedDB data outside the ".then" is working. So I created a boolean variable and tried updating it inside the ".then" and thought of updating the IndexedDB data outside but the boolean value is not getting updated inside the ".then".

.then(() =>{
        data_inserted = true ;
      })

Now outside the ".then"

console.log(data_inserted); // value is false
      if ( data_inserted === true )
      {
// update IndexedDB code
      }

I saw this post post-link and I'm not sure how to do a callback function as they did for my code.

Kindly help me in updating the boolean variable.

Thanks in advance.

sureshtechi
  • 145
  • 5
  • 15
  • 1
    Could you provide more of the surrounding code? Specifically, where are you declaring "data_inserted"? – lowcrawler Jun 18 '22 at 20:48
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – jonrsharpe Jun 21 '22 at 12:03

1 Answers1

3

I suspect this is a lack of understanding of async code.

The async code, then, will happen AFTER the code that follows it. Note:

let foo = "bar"
someFunctionThatTakesOneSecond()
    .then((res) => {
        foo = "baz"
        console.log("then: ", foo); 
    })
console.log("there: ", foo)

Will output:

 there: bar
 then: baz

Why? Because the code in the 'then' won't run until after `someFunctionThatTakesOneSecond" completes and the promise is fulfilled. But the code after the async block will run synchronously (ie: right away).

You may wish to use the async/await pattern instead - await stops further execution until the async function returns.

So:

let foo = "bar"
await someFunctionThatTakesOneSecond()
foo = "baz"
console.log("then: ", foo); 
console.log("there: ", foo)

Would output:

 then: baz
 there: baz

Read more on async/await and asynchronous JavaScript here: https://blog.logrocket.com/understanding-asynchronous-javascript/

lowcrawler
  • 6,777
  • 9
  • 37
  • 79