【问题标题】:How to send a response only after a query has been executed in loopback如何仅在环回中执行查询后发送响应
【发布时间】:2017-03-09 00:02:04
【问题描述】:

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

 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(response)。只有在复杂部分完成并且数据被正确添加到该数据的响应后,我才能发送响应。当数据被推入 for 循环时,我无法在复杂部分内移动 cb(response)。 听说过promise,这里可以用吗,如果可以,怎么做? 有人请帮忙!!

【问题讨论】:

  • 你能试试error first callback吗?您正在寻找的响应可能是回调中的第二个参数,所以如果 resnull 这实际上意味着没有发生错误。
  • 您需要异步执行循环。请显示一些循环代码
  • @JustinHellreich 我已经在使用错误优先回调。对不起,我在示例代码中错过了它。
  • @EbrahimPasbani 我将使用循环代码更新问题。
  • 您正在向Model.find 传递一个回调,这不是第一个错误。

标签: node.js loopbackjs


【解决方案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);
        }
    });
}

【讨论】:

  • 我有一个疑问,成功的cb()会写在哪里?
  • 感谢您的帮助。我正在尝试。
  • @DevStar 成功的部分来自if (alertRelAlert) {...。我在代码中将其从主代码中移出,但为了简单起见,我错过了这一点
  • 如果循环内需要另一个查找查询该怎么办?
  • @DevStar 对于这种情况async是一个不错的选择
猜你喜欢
  • 2016-04-15
  • 1970-01-01
  • 2011-03-23
  • 2015-10-20
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 2021-07-05
相关资源
最近更新 更多