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



我正在循环通过一堆帖子,并在循环中进行多个异步调用。我相信我理解这个问题,但是希望有一个替代解决方案,而不是对我而想起的解决方案。到第一个异步呼叫完成并触发第二个异步呼叫时,所有帖子都已循环,现在邮政为最后一个帖子。

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)
    })
  })
}

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

使用让:

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

let具有重新固定每次迭代的循环变量的特征。

let除了您可以使用postIDs.foreach()

最新更新