Express:forEach完成后渲染视图

时间:2019-05-15 08:47:14

标签: javascript node.js express

我有正在循环内执行的更新查询。

我想在forEach循环完成迭代后呈现视图。

代码:

conn.query(`SELECT Id, ${sfColumn} from Lead`, function (err, result) {
                if (err) { return console.error(err) }

                var resultData = result.records

                resultData.forEach(element => {

                    var sfColumnValue = null
                    if (element[sfColumn] == null) {
                        sfColumnValue = null
                    } else {
                        sfColumnValue = "'" + element[sfColumn] + "'"
                    }

                    var updateSql = `UPDATE leads SET ${localColumn} = ${sfColumnValue} WHERE sid = '${element.Id}'`

                    dbConfig.varConnection[dbName].query(updateSql, function (err, data) {
                        if (!err) {
                            console.log("data", data)
                            // res.render('updated.ejs')
                        }
                        else
                            console.log('Error while performing Query.', err);
                    });
                })
            })

1 个答案:

答案 0 :(得分:4)

您可以使用索引:

resultData.forEach((element, index) => {
    /*...*/
});

,然后添加以下条件以发送响应:

if (index === resultData.length - 1) {
    res.render('updated.ejs')
}

完整代码:

conn.query(`SELECT Id, ${sfColumn} from Lead`, function (err, result) {
    if (err) { return console.error(err) }

    var resultData = result.records

    resultData.forEach((element, index) => {

        var sfColumnValue = null
        if (element[sfColumn] == null) {
            sfColumnValue = null
        } else {
            sfColumnValue = "'" + element[sfColumn] + "'"
        }

        var updateSql = `UPDATE leads SET ${localColumn} = ${sfColumnValue} WHERE sid = '${element.Id}'`

        dbConfig.varConnection[dbName].query(updateSql, function (err, data) {
            if (!err) {
                console.log("data", data)
                if (index === resultData.length - 1) {
                    res.render('updated.ejs')
                }
            }
            else
                console.log('Error while performing Query.', err);
        });
    })
});