2

我正在嘗試創建一個觸發器,它會將測試分數相加,然後根據以前的測試結果計算學生放置位置。Firebase的雲端函數 - 以承諾循環播放

我試圖如下所示內利用承諾爲循環:

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 index; 

     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()); 

       }); 

     }).catch(reason => { 

       // Handle Error 
       console.log(reason); 

     }); 
    } 
} 

其中有人告訴我,在這個post看到是行不通的。

"Once a promise is resolved or rejected, it forever retains that state and can't be used again. To repeat the work, I think you'd have to construct another chain of new promises representing the second iteration of work."

我一直在試圖調整自己的觸發,但我無法弄清楚,我將如何構建的承諾,以實現我想要的結果的新鏈?有沒有人遇到並克服過這個問題?

我希望實現的是使觸發迭代四(4)反覆section行爲等於4

我需要利用其他承諾迭代不會正確完成,具體testScr += parseInt(nValue[i]);和查找總結和形成。

但作爲明確規定,通過承諾,例外只迭代一審正常使用,而不是當i = 2 or 3 or 4

+0

您分享的代碼不是雲端函數。我不太清楚你是如何觸發這種情況的,你期望什麼樣的行爲,以及你實際得到了什麼樣的行爲。請正確地更新您的問題。你還需要在最內層的'once()'回調中修復未終止的字符串。 –

+0

它只執行一次迭代,因爲你在循環中間用'return'語句返回整個函數。放置一個'return'將不允許循環結束。 –

+0

@DougStevenson您指的是哪個回報?!你能否提供我應該如何構建我的代碼。 – Learn2Code

回答

0

這種做法是不是乾淨,但可能會幫助您。

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 index; 

    admin.database().ref('TestScores').child(data.key).child('Summative').child(i).once("value").then(x => { 
     xIndex = x.val(); 
     return { xIndex, index: i }; 
    }).then(({ xIndex, index}) => { 
     admin.database().ref('TestScores').child(data.key).child('Formative').child(index).once("value").then(y => { 
     yIndex = y.val(); 
     return { yIndex, xIndex }; 
     }).then(({ yIndex, xIndex}) => { 
     admin.database().ref('StudentPlacement').child(data.key).child(xIndex + ":" + yIndex).once("value", snapshot => { 
      console.log("Student Placement is: ", snapshot.val()); 
     }); 
     });   
    }).catch(reason => { 
     console.log(reason); 
    }); 
    } 
});