在foreach Node.js Promis中查询

时间:2018-04-20 10:21:44

标签: mysql node.js promise

我在每个承诺中放入查询。我试图两次查询mysql数据库,第二次,第一次从每次结果多次查询,但我无法确定如何在继续之前等待第二个查询的结果

我希望输出如下:

{
   "data":[
      {
         "name":"Title result",
         "images":[
            {
               "id":1,
               "place_id":705,
               "path_image":"http://3.bp.blogspot.com/-iwF-ImFpzvk/T6fKhC6F7YI/AAAAAAAAARA/FyKpNcDsP8M/s1600/asd2e1.jpg"

            },
            {
               "id":2,
               "place_id":705,
               "path_image":"https://asrt.bp.com/data/photo/2014/07/22/sddrfr2.jpg",
            }
         ]
      }
   ]
}

但我只是这样:

{
   "data":[
      {
         "name":"Title result",
         "images":[]
}

这是我的代码:

return new Promise((resolve, reject) => {
                const { connection, errorHandler } = deps;
                let arrayData = [];
                let imageData = [];

                connection.query(
                    "SELECT * FROM places WHERE id = 705",
                    (error, rows, results) => {
                        rows.forEach((row) => {
                            connection.query(
                                "SELECT * FROM place_gallery WHERE place_id = 705",
                                (error, rows, results) => {
                                    imageData = rows;

                                }
                            )
                            arrayData.push({ name: row.title, images: imageData })


                        });

                        if (error) {
                            errorHandler(error, "failed", reject);
                            return false;
                        }
                        resolve({ data: arrayData });

                    }
                );

            })
        },

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

试试这个,另一种创建dbcall函数的方法,您可以使用util.promisify()

将查询回调转换为promise
const dbcall = (query) => {
    return new Promise((resolve, reject) => {
        connection.query(
            query,
            (error, rows, results) => {
                if (error) return reject(error);
                return resolve(rows);
            });
    });
};

const somefunc = async () => {
    const {
        connection,
        errorHandler
    } = deps;
    let arrayData = [];
    try {
        const rows = await dbcall("SELECT * FROM places WHERE id = 705");
        rows.forEach(async (row) => {
            const imageData = await dbcall("SELECT * FROM place_gallery WHERE place_id = 705");
            arrayData.push({
                name: row.title,
                images: imageData
            });
        });
    } catch (error) {
        console.log(error);
    }
    return arrayData;
}