使用node.js和$ q的Promise

时间:2017-11-10 08:05:10

标签: javascript node.js mongodb express promise

我在node.js中有一个简单的应用程序,mongoDB作为数据库。 我试图从集合中检索一个值,然后对数据进行一些调整,然后将其返回给用户。

我从mongoDB中检索值,然后我动态调整它,我能够在调试模式下看到新项目有效并保存更新的值。

但是在流程结束时,当我尝试将值返回给请求的调用者时,deferred.resolve(appSettings) aint工作正常。

我被置于无休止的循环中。我在调试时设法看到的是我设法在控制器中捕获错误(在无限循环之前)

then(function (item) {
                res.Send(item);
            })
            .catch(function (err) {
                res.Status(400).Send(err);
            });

区域,它会写入以下错误消息 - res.Send is not a function

代码:

uiSettings.service.js -

var config = require('config.json');
var dateUtil = require('date-and-time')
var Q = require('q');
var mongo = require('mongoskin');
var db = mongo.db(config.connectionString, { native_parser: true });
db.bind('UiAppSettings');

var service = {};

service.getOneByMappingType = getOneByMappingType

module.exports = service;

function getOneByMappingType(mappingType){
    var deferred = Q.defer();

    db.UiAppSettings.findOne(
        { MappingType: mappingType},
        function (err, appSettings){
            if (err) deferred.reject(err.name + ': ' + err.message);

            if(appSettings)
                adjustDates(appSettings);

            deferred.resolve(appSettings);

        });

        function adjustDates(appSettings){
            var defaultDates = appSettings.UiSettingsMap.FilterObject.Time.Defaults;
            for (var i=0; i< defaultDates.length; i++)
            {
                var startDate = calculateDate(defaultDates[i].StartDefaultsDate);
                var endDate = calculateDate(defaultDates[i].EndDefaultsDate);
                appSettings.UiSettingsMap.FilterObject.Time.Defaults[i].startDate = startDate;
                appSettings.UiSettingsMap.FilterObject.Time.Defaults[i].endDate = endDate;
            }
            appSettings.UiSettingsMap.FilterObject.Time.Selected.startDate = appSettings.UiSettingsMap.FilterObject.Time.Defaults[0].startDate;
            appSettings.UiSettingsMap.FilterObject.Time.Selected.endDate = appSettings.UiSettingsMap.FilterObject.Time.Defaults[0].endDate;

        }

        function calculateDate(dateData){
            let currDate = new Date();
            currDate = dateUtil.addYears(currDate, dateData.Year);
            currDate = dateUtil.addMonths(currDate, dateData.Month);
            currDate = dateUtil.addDays(currDate, dateData.Day);
            return currDate;
        }

    return deferred.promise;
}

uiSettings.controller.js ----

var config = require('config.json');
var express = require('express');
var router = express.Router();
var uiService = require('services/uiSettings.service');

// routes
router.get('/:mappingType', getOneByMappingType)


module.exports = router;


function getOneByMappingType(req, res){
    uiService.getOneByMappingType(req.params.mappingType)
        .then(function (item) {
            res.Send(item);
        })
        .catch(function (err) {
            res.Status(400).Send(err);
        });
}

---- server.js

require('rootpath')();
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


// routes
app.use('/settings', require('./controllers/uiSettings.controller'));

// start server
var port = process.env.NODE_ENV === 'production' ? 80 : 4000;
var server = app.listen(port, function () {
    console.log('Server listening on port ' + port);
});

1 个答案:

答案 0 :(得分:0)

正如jfriend00评论的那样,问题是由于使用Send而不是send的区分大小写。

我也接受了Neil的建议,并做了很多改动,使用内置的原生Promise和原生的mongo驱动程序。