Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对于具有多个异步调用的循环-重复打印第二个异步函数中的最后一项_Javascript_Firebase_Asynchronous_Firebase Realtime Database - Fatal编程技术网

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

Javascript 对于具有多个异步调用的循环-重复打印第二个异步函数中的最后一项,javascript,firebase,asynchronous,firebase-realtime-database,Javascript,Firebase,Asynchronous,Firebase Realtime Database,我在一堆帖子中循环,并在循环中执行多个异步调用。我相信我理解这个问题,但我希望有一个替代的解决方案,而不是我想到的那个。当第一个异步调用完成并触发第二个异步调用时,所有postID都已循环,postID现在设置为最后一个postID var postIDs = { "abcdef": true "bbb456": true "ccc123": true } for(var postID in postIDs) { console.log("postID = " +

我在一堆帖子中循环,并在循环中执行多个异步调用。我相信我理解这个问题,但我希望有一个替代的解决方案,而不是我想到的那个。当第一个异步调用完成并触发第二个异步调用时,所有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
具有在每次迭代时重新绑定循环变量的功能


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

您尝试过使用let而不是var吗?我没有,但我应该有。谢谢你的建议@DaveCast