gpt4 book ai didi

javascript - 具有多个异步调用的 For 循环 - 重复打印第二个异步函数中的最后一项

转载 作者:行者123 更新时间:2023-12-03 02:50:02 26 4
gpt4 key购买 nike

我正在循环浏览一堆帖子并在循环内执行多个异步调用。我相信我理解这个问题,但我希望有一种替代解决方案,而不是我想到的解决方案。当第一个异步调用完成并触发第二个异步调用时,所有 postID 都已循环完毕,并且 postID 现在设置为最后一个 postID。

var postIDs = {
"abcdef": true
"bbb456": true
"ccc123": true
}

for(var postID in postIDs) {
console.log("postID = " + postID);
// check that the postID is within the postIDs to skip inherited properties
if (postIDs.hasOwnProperty(postID)) {
// make one async call
admin.database().ref().child('posts').child(postID).limitToLast(1).once('value').then(snapshotForMostRecentPost => {
// make a second async call
admin.database().ref().child('anotherBranch').child('someChild').once('value').then(snapshotForSomeOtherStuff => {
console.log("postID = " + postID) // **ISSUE**: the postID is always `ccc123`
// do some more stuff with the postID
})
})
}
}

我想要的结果是这样的:

abcdef
bbb456
ccc123

相反,我得到了这个结果:

ccc123
ccc123
ccc123
<小时/>

可能的解决方案

我能想到解决这个问题的一种方法是将异步调用放入它们自己的函数中并调用该函数,如下所示:

var postIDs = {
"abcdef": true
"bbb456": true
"ccc123": true
}

for(var postID in postIDs) {
console.log("postID = " + postID);
// check that the postID is within the postIDs to skip inherited properties
if (postIDs.hasOwnProperty(postID)) {
triggerThoseAsyncCalls(postID)
}
}

function triggerThoseAsyncCalls(postID) {
// make one async call
admin.database().ref().child('posts').child(postID).limitToLast(1).once('value').then(snapshotForMostRecentPost => {
// make a second async call
admin.database().ref().child('anotherBranch').child('someChild').once('value').then(snapshotForSomeOtherStuff => {
console.log("postID = " + postID)
})
})
}
<小时/>

但是,我更愿意将其保留为一个函数。 有人知道解决此问题的方法,而无需将异步调用分离到单独的函数中吗?

最佳答案

使用let代替:

for(let postID in postIDs) { ... }

let 具有在每次迭代时重新绑定(bind)循环变量的功能。

除了let之外,您还可以使用postIDs.foreach()

关于javascript - 具有多个异步调用的 For 循环 - 重复打印第二个异步函数中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47916483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com