ループの中で複数の非同期呼び出しを実行しています。私はこの問題を理解していると信じていますが、私にとっては別の解決策が望まれます。最初の非同期呼び出しが終了して2番目の非同期呼び出しをトリガーするまでに、すべてのpostIDがループされ、postIDが最後のpostIDに設定されます。複数の非同期呼び出しを持つForループ - 2番目の非同期関数の最後の項目を繰り返し印刷します。
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
以外はvarではなく聞かせて使用してみましたか? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let – DaveCoast
*顔の手のひら*私は持っていたが、私は持っていたはずだった。提案をありがとう@DaveCoast – Rbar