2017-12-12 10 views
0

데이터베이스에서 특정 데이터를 검색하려면 2 firebase calls을 실행해야합니다. Once these promises resolve, 검색된 데이터가있는 다른 함수를 호출하고 싶습니다. 어떻게해야합니까? 아래 Promise.All?여러 firebase 약속을 실행 한 다음 한 번 완료되면 함수를 실행하십시오

코드와 ..something :

app.post('/testtwilio', function(req, res) { 
    //save request variables 
    var to_UID = req.body.to; 
    var from_UID = req.body.from; 
    var experience_id = req.body.exp_id; 

    //Query firebase and save 'zone_id' which we need later 
    firebase.database().ref('experiences').child(experience_id).once('value').then((snap) => { 
    zone_id = snap.val().ZoneID; 
    }); 

    //Query firebase and save 'from_name' which we need later 
    firebase.database().ref('users').child(from_UID).once('value').then((snap) => { 
    from_name = snap.val().Name; 
    }); 

    //Once we have the two variables returned and saved 
    //Call a final firebase query and a twilio function with all the recieved data 
    firebase.database().ref('users').child(to_UID).once('value').then((snap) => { 
    //Do something with this aggregated data now 
    client.messages.create({ 
     //blah blah do something with the saved data that we retrieved 
     var phone = snap.val().Phone; 
     var msg = from_name + zone_id + from_UID + experience_id 
    }); 
    }); 
}); 

답변

1

예, Promise.allonce('value') 이후 반환 하나를 사용할 수 있습니다.

빠른 아주 간단한 예 :

var promises = []; 
promises.push(firebase.database().ref('experiences').child(experience_id).once('value')); 
promises.push(firebase.database().ref('users').child(from_UID).once('value')); 

// Wait for all promises to resolve 
Promise.all(promises).then(function(res) {   
    // res[0] is your experience_id snapshot 
    // res[1] is your from_UID snapshot 
    // Do something... 
}); 
1

당신은 버전 7.6의 NodeJS를 사용하고 높은 당신은 또한 읽고 유지하기 위해 훨씬 더 간단을 비동기 기능이 코드를 작성할 수있는 경우

// ... 

const wrap = require('express-async-wrap') 

// ... 
         // need to wrap async function 
         // to make it compatible with express 
app.post('/testtwilio', wrap(async (req, res) => { 
    const to_UID = req.body.to 
    const from_UID = req.body.from 
    const experience_id = req.body.exp_id 

    const [ 
    snap1, 
    snap2, 
    snap3 

    // waiting for all 3 promises 
    ] = await Promise.all([ 
    firebase.database().ref('experiences').child(experience_id).once('value'), 
    firebase.database().ref('users').child(from_UID).once('value'), 
    firebase.database().ref('users').child(to_UID).once('value') 
    ]) 

    const zone_id = snap1.val().ZoneID 
    const from_name = snap2.val().Name 
    const phone = snap3.val().Phone 
    const msg = from_name + zone_id + from_UID + experience_id 

    // ... 
    client.messages.create(...) 
}))