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