複数の非同期呼び出しを伴うForループ-2番目の非同期関数の最後の項目を繰り返し出力します

Rbar

私はたくさんの投稿をループしていて、ループ内で複数の非同期呼び出しを行っています。私はこの問題を理解していると思いますが、私が思い浮かぶ解決策とは別の解決策を望んでいます。最初の非同期呼び出しが終了して2番目の非同期呼び出しがトリガーされるまでに、すべての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 

考えられる解決策

これを解決するために私が考えることができる1つの方法は、非同期呼び出しを独自の関数に入れ、その関数を次のように呼び出すことです。

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

ただし、これを1つの関数として保持したいと思います。非同期呼び出しを別の関数に分離せずにこれを解決する方法を知っている人はいますか?

ベスリンダN。

代わりにletを使用してください:

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

let 反復ごとにループ変数を再バインドする機能があります。

let使用できる以外postIDs.foreach()

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ