NodeJS:如何在promise循环中返回MySQL查询的响应

时间:2018-04-06 12:24:24

标签: mysql node.js for-loop promise

我有一系列事件。在承诺和循环的帮助下,我试图让每个活动的成员。但它正在回复查询。这是我的代码:

var promiseArray = [];
rows.forEach(function (element) {
    element.members = db.query("MySQL query");
    promiseArray.push(element);
});

return Promise.all(promiseArray).then((data) => {
    response.send({data: data});
});

这是输出:

{"data":[{"id":346,"owner_id":1,"title":"test","description":"","location":"","location_latitude":"","location_longitude":"","event_date":"546456453","created_at":"1522674310271","members":{"domain":null,"_events":{},"_eventsCount":0,"_callSite":{},"_ended":false,"_idleNext":null,"_idlePrev":null,"_idleStart":null,"_idleTimeout":-1,"_repeat":null,"sql":"SELECT event_members.*, users.name, users.country_code, users.phone_number, users.profile_picture FROM event_members LEFT JOIN users ON event_members.user_id = users.id where event_members.event_id=346","typeCast":true,"nestTables":false,"_resultSet":null,"_results":[],"_fields":[],"_index":0,"_loadError":null}}]}

如果我执行以下查询:

var getEventMembersPromise = eventMembersModel.getEventMemberByEventId(element.id);
getEventMembersPromise.then(function (event_members) {
    element.members = event_members;
    promiseArray.push(element);
}, function (err) {
    response.status(422).send({msg: commonFunctions.getErrorMessage(2)});
    return true;
}).catch((err) => {
    response.status(422).send({msg: commonFunctions.getErrorMessage(2)});
    return true;
});

它返回空数组。

0 个答案:

没有答案