1

我很努力解決這個問題,因爲我是Promises的新手。問題構建循環中的承諾

我需要首先讀無論從火力地堡的SummativeFormative之前我可以確定StudentPlacement

方式下面的代碼,提供null作爲StudentPlacement snapshot.val(),因爲它是不等待xy值。

exports.boxScoresUpdate = functions.database.ref('/Tests/{id}/TestScores').onWrite(event => { 

    let testScr = 0; 

    for (let i = 1; i <= section; i++) { 
     // 
     testScr += parseInt(nValue[i]); 

     var xIndex = 0; 
     var yIndex = 0; 


     admin.database().ref('TestScores').child(data.key).child('Summative').child(i).once("value").then(x => { 

      xIndex = x.val(); 

     }); 

     admin.database().ref('TestScores').child(data.key).child('Formative').child(i).once("value").then(y => { 

      yIndex = y.val(); 

     }); 

     admin.database().ref('StudentPlacement').child(data.key).child(xIndex + ":" + yIndex).once("value", snapshot => { 

      // SnapShot 
      console.log("Student Placement is: ", snapshot.val()); 

     }); 

    } 

} 

誰能幫我構建了扳機!?

回答

1

您正在等待兩個函數在執行下一個代碼之前完成。看看Promise.all

for (let i = 1; i <= section; i++) { 
    const xIndexRef = admin.database().ref('TestScores').child(data.key).child('Summative').child(i).once("value"); 
    const yIndexRef = admin.database().ref('TestScores').child(data.key).child('Formative').child(i).once("value"); 

    Promise.all([xIndexRef, yIndexRef]) 
     .then(results => { 
     const xSnapshot = results[0]; 
     const ySnapshot = results[1]; 

     return admin.database().ref('StudentPlacement').child(data.key).child(xSnapshot.val() + ":" + ySnapshot.val()).once("value"); 
     }) 
     .then(snapshot => { 
     console.log("Student Placement is: ", snapshot.val()); 
     }); 
} 

Promise.all等待兩xIndexRefyIndexRef完成其執行。

一旦執行結果返回到一個可執行的對象。

您可以訪問結果並完成執行。

+0

感謝您對此提供的幫助......它工作的非常好,正如我設想的那樣正常工作! – Learn2Code