javascript - 问题在循环中构造一个 promise

标签 javascript firebase firebase-realtime-database promise google-cloud-functions

我正在努力解决这个问题,因为我是 Promises 的新手。

我需要先阅读 Firebase 的 SummativeFormative,然后才能确定 StudentPlacement

下面的代码提供了 null 作为 StudentPlacement snapshot.val(),因为它不等待 x 并且y 值。

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

        });

    }

}

谁能帮我构建触发器!?

最佳答案

在执行下一段代码之前,您正在等待这两个函数完成。查看 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 完成它们的执行。

一旦执行,结果将返回到一个 thenable 对象中。

您可以访问结果并完成执行。

关于javascript - 问题在循环中构造一个 promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45685996/

相关文章:

javascript - 当我尝试在 ExtendScriptTK 中调试用于 indesign 的脚本时,我得到的 app.documents 是未定义的,如果我从 indesign 运行脚本它会工作

python - 如何在 Python 中将文档 ID 添加到 firestore 文档

android - 当用户尝试在移动浏览器中点击动态链接时如何打开android应用程序

javascript - 将数据从 javascript 传递到 HTML 标记

javascript - 根据位置获取数组中的N个元素

javascript - 在 Cloud Functions for Firebase 中启用 CORS

java - 加载购物车数据时显示空字段

javascript - 向新用户发送电子邮件 firebase

swift 、Firebase : `setValue` giving error "AnyObject cannot be used with Dictionary Literal"

Windows 中的 Javascript 本地化