Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
variable updated inside ".then" in fetch not reflected outside in Javascript

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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/

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!