提问者:小点点

node.js将图像数组添加到相应的数组中


我是Node.js的新手,我正在从数据库(操作)中获取一些数据。每个操作都在另一个表中注册了许多图像,这样我就可以通过操作ID获取它们。

我正在尝试将这些图像的数组添加到相关操作中,这样我就可以在前端循环遍历它们。

在php中,我经常这样做:

    $return = array();
    $images = array();
    $image = array();

    $select = "SELECT id, title, description FROM actions WHERE id = ? order by id DESC";
    $stmt = $mysqli->prepare($select);
    $stmt->bind_param('s', $id);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id, $title, $description);

    while ($stmt->fetch()) {
        $registers = array(
            "id" => $id, "title" => $title, "description" => $description, "images" => $image
        );

        $selectImages = mysqli_query($mysqli, "SELECT id, image FROM action_images WHERE action_id = '" . $id . "' ");
        while ($row = $selectImages->fetch_array(MYSQLI_BOTH)) {

            $images = array("imageID" => $row['id'], "image" => $row['image']);
            array_push($registers["images"], $images);
        }
        
        $return[] = $registers;

    }

javscript/node.js中有类似的内容吗?我尝试了下面代码中描述的一些事情,但没有像预期的那样工作。

这是我的控制器:

async selectActions(req, res) {

        let actionData = [];

        conn.execute('SELECT * FROM actions',
            function (err, results, fields) {

                // console.log(err);
                // console.log(results);

                if (err == null) {

                    results.forEach(action => {
                        conn.execute('SELECT * FROM actions_images WHERE actionID = ?',
                            [action.id],
                            function (imagesError, imagesResults, ImagesFields) {

                                // I've tried some things like:
                                actionData = [results, imagesResults];
                                // and
                                actionData = [...results, ...imagesResults]
                                // and
                                results.push(imagesResults)
                                // but nothing had the expected results displayed in the image below
                                console.log(actionData);
                            }
                        );
                    });

                    return res.json(results);
                } else {
                    return res.json('error fetching actions from database: ' + err);
                }
            });

    },

操作图像数组必须是每个操作项中的另一项:


共1个答案

匿名用户

试试这个...

Promise.all(results.map((action, index) => {
    return Promise(resolve => {
        conn.execute('SELECT * FROM actions_images WHERE actionID = ?',
            [action.id],
            function(imagesError, imagesResults, ImagesFields) {
                results[index].action_images = imagesResults;
                resolve(true);
            }
        );
    })

}))
console.log(results);