簡體   English   中英

在 fetch 中更新的“.then”內部變量未反映在 Javascript 外部

[英]variable updated inside ".then" in fetch not reflected outside in Javascript

我嘗試在 fetch 中更新“.then”中的 IndexedDB 數據,但這在事件處理程序中不起作用,因為我從這篇post-link中了解到這一點。 更新“.then”之外的 IndexedDB 數據正在工作。 所以我創建了一個布爾變量並嘗試在“.then”中更新它,並考慮在外部更新 IndexedDB 數據,但布爾值沒有在“.then”中更新。

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

現在在“.then”之外

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

我在鏈接后看到了這篇文章,但我不確定如何像他們為我的代碼所做的那樣執行回調函數。

請幫助我更新布爾變量。

提前致謝。

我懷疑這是對異步代碼缺乏了解。

then ,異步代碼將發生在它后面的代碼之后。 筆記:

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

將輸出:

 there: bar
 then: baz

為什么? 因為 'then' 中的代碼要等到 `someFunctionThatTakesOneSecond' 完成並實現 promise 之后才會運行。但是 async 塊之后的代碼將同步運行(即:立即)。

您可能希望改用 async/await 模式 - await會停止進一步執行,直到 async 函數返回。

所以:

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

會輸出:

 then: baz
 there: baz

在此處閱讀有關 async/await 和異步 JavaScript 的更多信息: https ://blog.logrocket.com/understanding-asynchronous-javascript/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM