2017-12-21 4 views
0

나는 많은 게시물을 반복하면서 루프 내에서 여러 비동기 호출을 수행합니다. 나는이 문제를 이해한다고 믿지만 나에게 떠오르는 해결책보다 더 나은 대안을 기대하고있다. 첫 번째 비동기 호출이 끝나고 두 번째 비동기 호출이 트리거 될 때까지 모든 postID가 반복되고 postID가 마지막 postID로 설정됩니다. 나는이 결과를 얻을, 대신다중 비동기 호출이있는 For 루프 - 두 번째 비동기 함수에서 마지막 항목을 반복적으로 인쇄합니다.

abcdef 
bbb456 
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)) { 
    // 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 
     }) 
    }) 
    } 
} 

내가 목표로하고 결과는 이것이다

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

나는, 그러나, 하나 개의 함수로 이것을 유지하는 것을 선호합니다. 비동기 호출을 별도의 함수로 분리하지 않고이를 해결하는 방법을 아는 사람이 있습니까?

+2

을 사용할 수 있습니다 let 이외의

는 var 대신 할 사용하여 시도 적이 있습니까? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let – DaveCoast

+0

* 얼굴 손바닥 * 나는 가지고 있어야만 했었습니다. 제안을 주셔서 감사합니다 @DaveCoast – Rbar

답변

1

사용 대신하자

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

let 각 반복에서 루프 변수를 리 바인딩의 기능이 있습니다. 당신이 postIDs.foreach()

+0

아 물론! 아름답게 일했습니다 .. 많은 감사합니다! – Rbar