如何在环回执行查询后才发送响应

时间:2017-03-08 15:20:43

标签: node.js loopbackjs

我在环回中有一个远程方法,如:

 Alerts.getAlertDetails = function (alertId, options, cb) {
        var response = {};
        var userId = options.accessToken.userId;
        Alerts.app.models.MobileUserAlertRelation.find({where: {userId: userId, alertId: alertId, isDeleted: -1}, include: {relation: 'alerts', scope: {include: ['alertTypes'], where: {status: 1}}}}, function (err, alertRel) {


            if (alertRel.length > 0 && alertRel[0].alerts()) {
                response.code = 200;
                response.status = "success";
                response.data = {};

                if (alertRel[0].alertId) {
                    response.data.alertId = alertRel[0].alertId;
                }
                if (alertRel[0].readStatus) {
                    response.data.readStatus = alertRel[0].readStatus;
                }
                if (alertRel[0].receivedOn) {
                    response.data.alertReceivedOn = alertRel[0].receivedOn;
                }

                var alertData = alertRel[0].alerts();
                if (alertData.title) {
                    response.data.alertTitle = alertData.title;
                }
                if (alertData.message) {
                    response.data.alertShortMessage = alertData.message;
                }
                if (alertData.extraMessage) {
                    response.data.alertMessage = alertData.extraMessage;
                }
                if (alertData.priority) {
                    response.data.alertPriority = alertData.priority;
                }
                if (alertData.validUntil) {
                    response.data.alertExpiresOn = alertData.validUntil;
                }
                if (alertData.images && alertData.images.length > 0) {
                    response.data.alertImages = [];
                    for (var image in alertData.images) {
                        if (alertData.images.hasOwnProperty(image)) {
                            response.data.alertImages.push(constants.ALERT_IMAGE_URL + '/' + alertData.images[image]);
                        }
                    }

                }
                if (alertData.alertTypes() && alertData.alertTypes().alertTypeName) {
                    response.data.alertType = alertData.alertTypes().alertTypeName;
                }

                if (alertData.alertLocations && alertData.alertLocations > 0) {
                    response.data.alertLocations = [];
                    response.data.policeDepartments = [];
                    response.data.hospitals = [];
                    response.data.fireDepartments = [];
                    var locations = alertData.alertLocations;
                    for (var locKey in locations) {
                        if (locations.hasOwnProperty(locKey)) {
                            if (locations[locKey].data) {
                                response.data.alertLocations.push(locations[locKey].data);

                                console.log(locations[locKey].data);
                                if (locations[locKey].data.type) {
                                    var locationType = locations[locKey].data.type;
                                    if (locationType === "Polygon") {
                                        var coordinates = locations[locKey].data.coordinates[0];
                                        var polygonCenter = getPolygonCenter(coordinates);
                                        console.log(polygonCenter);
                                    }
                                }
                            }
                        }
                    }
                }
                cb(null, response);
            } else {
                response.code = 404;
                response.status = 'error';
                response.message = 'Alert not found.';
                cb(null, response);
            }
        })
    };

但是当我通过api调用此方法时,会收到响应,而不会从复杂的代码部分添加数据。我知道回调将在这里异步调用,因此在复杂代码完全执行之前将调用cb(响应)。如何在完成复杂零件并将数据正确添加到该数据的响应后才能发送响应。当数据被推入for循环时,我无法在复杂部分内移动cb(响应)。 我听说过承诺,可以在这里使用,如果是的话,怎么办呢? 有人请帮忙!!

1 个答案:

答案 0 :(得分:1)

问题是因为在if中提取关系。

关系方法是异步。

Alerts.getAlertDetails = function (alertId, options, cb) {
        var response = {};
        var userId = options.accessToken.userId;
        Alerts.app.models.MobileUserAlertRelation.find({where: {userId: userId, alertId: alertId, isDeleted: -1}, include: {relation: 'alerts', scope: {include: ['alertTypes'], where: {status: 1}}}}, function (err, alertRel) {

        if(alertRel.length < 1){
        return handleError();
        }

        alertRel[0].alerts(handleResponse);

        function handleResponse(err, alertRelAlert){
                if(err) return handleError();

                    if (alertRelAlert) {
                //all that code in question if if section
                }else {
                return handleError();
                }
        }

        function handleError(){
        response.code = 404;
                response.status = 'error';
                response.message = 'Alert not found.';
                cb(null, response);
        }
    });
}