Home > Software engineering >  variable updated inside ".then" in fetch not reflected outside in Javascript
variable updated inside ".then" in fetch not reflected outside in Javascript

Time:06-19

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.

CodePudding user response:

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/

  • Related