假設專案通過推送頻繁地被添加到一個陣列中。另一個異步函式(在 setInterval 背景關系中獨立運行)將隨機專案從陣列中移除。
在第二個函式中,當我在一行中評估要移除的專案的索引時,在我到達下一行進行 array.splice(index, 1) 之前,陣列可能發生變化。對嗎?錯誤的專案會被洗掉。
我應該如何解決這個問題?
我應該如何解決這個問題?
編輯:示例:
async function analyze() {
letpendingTxs = [] 。
web3.eth.subscribe('pendingTransactions',function(error, result){
if (error) console.log(error)。
})
.on("data"/span>, async function(hash){
pendingTxs.push(hash)
})
setInterval(async ( ) => {
let promises = pendingTxs.map(pTx => {return web3. eth.getTransaction(pTx) })
let updatedTransactions = await Promise.all(promises)
for (let index = 0; index < updatedTransactions.length; index ) {
const txUpdated = updatedTransactions[index];
if (txUpdated.transactionIndex != null) {
const index = pendingTxs.indexOf(txUpdated.hash)
if (index > -1) {
pendingTxs.splice(index, 1) 。
}
}
}
},250)
}
analyze()
編輯2:我認為Chris在這種情況下可能是正確的。
uj5u.com熱心網友回復:
不。
const index = pendingTxs.indexOf(txUpdated.hash)
if (index > -1) {
pendingTxs.splice(index, 1) 。
作為一個單元運行。
JavaScript的async函式是合作的,而不是搶先的。
在合作式多任務處理中,[控制器]從不啟動從正在運行的[執行緒]到另一個[執行緒]的背景關系切換。只有當[執行緒]自愿讓出控制權時,才會發生背景關系切換。
由于JS是基于事件回圈并發
因此,如果你做了一個await或yield,那么其他代碼可能會運行,但如果你沒有明確地做這些暫停動作之一,那么上面的指令會作為一個單元運行。
SharedArrayBuffers是一個例外,因為主機被允許廣泛共享其內容,但Arrays卻不能這樣共享。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/334242.html
標籤:
上一篇:在C#中對二維陣列進行零填充
