我有一个使用mongoose创建对象的服务方法,我试图从回调重写为promises:
var Booking = require("../models/booking");
var Promise = require('bluebird');
var notificationEmitter = require('../events/notificationEmitter').NotificationEmitter;
exports.createBooking = function(/* many arguments */){
var booking = new Booking();
... omitted details of adding to booking object...
booking.save().then(function(booking){
notificationEmitter.emit('createdBooking', booking);
return Promise.resolve(booking);
}).catch(function(err){
return Promise.reject(err);
});
};
在我的单元测试中:
bookingService.createBooking(/* all the required values */)
.then(function(booking){
assert.notEqual(booking, null);
done();
}).catch(function(err){
console.log(err);
assert.fail();
done();
});
但是我一直收到错误:
TypeError: Cannot call method 'then' of undefined
从我的单元测试。我已经调试了,最后一行是
return Promise.resolve(booking);
为什么我没有收到承诺?
答案 0 :(得分:2)
因为您未从createBooking
返回任何值。改为:
exports.createBooking = function(/* many arguments */){
var booking = new Booking();
// other code, and:
return booking.save().then(function(booking){
//^^^^ return here
notificationEmitter.emit('createdBooking', booking);
return Promise.resolve(booking);
}).catch(function(err){
return Promise.reject(err);
});
};