我嘗試在 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
}
我在鏈接后看到了這篇文章,但我不確定如何像他們為我的代碼所做的那樣執行回呼函式。
請幫助我更新布爾變數。
提前致謝。
uj5u.com熱心網友回復:
我懷疑這是對異步代碼缺乏了解。
異步代碼 ,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/
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494935.html
標籤:javascript 变量 索引数据库
