当用户输入促销代码时,此促销代码可能存在或不存在。我以这种方式返回错误,但是好像服务器崩溃了,它返回了很多行错误。 如何优化代码使其更简洁?这个表格正确吗?我对节点和JS的控制不多,很难看出哪种方法是最好的...
这是我在控制器中的代码:
var mongoose = require('mongoose'),
Promotion = mongoose.model('Promotion'),
q = require('q'),
Promise = q.Promise;
var PromotionController = {
applyPromo: function(promoCode) {
return new Promise(function(resolve, reject) {
if(promoCode === null) {
resolve(false);
}
Promotion.find({code: promoCode}, function (err, elements) {
if (err)
{
reject(err);
}
if((elements !== null) && (elements.length > 0)) {
console.log('OK');
console.log(elements[0]);
resolve(elements[0]._id);
}
else {
//reject(new Error('Doesnt exist ' + promoCode));
}
});
});
}
};
module.exports = PromotionController;
我的服务器显示:
Error: Doesnt exist codeExample
at /home/user/Documentos/myApi/myServer/api/controllers/promotions.js:36:13
at /home/user/Documentos/myApi/myServer/node_modules/mongoose/lib/model.js:4599:16
at /home/user/Documentos/myApi/myServer/node_modules/mongoose/lib/query.js:4122:12
at cb (/home/user/Documentos/myApi/myServer/node_modules/mongoose/lib/query.js:1777:14)
at result (/home/user/Documentos/myApi/myServer/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/home/user/Documentos/myApi/myServer/node_modules/mongodb/lib/utils.js:406:9)
at handleCallback (/home/user/Documentos/myApi/myServer/node_modules/mongodb/lib/utils.js:128:55)
at cursor.close (/home/user/Documentos/myApi/myServer/node_modules/mongodb/lib/operations/cursor_ops.js:224:62)
at handleCallback (/home/user/Documentos/myApi/myServer/node_modules/mongodb/lib/utils.js:128:55)
at completeClose (/home/user/Documentos/myApi/myServer/node_modules/mongodb/lib/cursor.js:893:14)
at Cursor.close (/home/user/Documentos/myApi/myServer/node_modules/mongodb/lib/cursor.js:912:10)
at cursor._next (/home/user/Documentos/myApi/myServer/node_modules/mongodb/lib/operations/cursor_ops.js:224:23)
at handleCallback (/home/user/Documentos/myApi/myServer/node_modules/mongodb-core/lib/cursor.js:204:5)
at _setCursorNotifiedImpl (/home/user/Documentos/myApi/myServer/node_modules/mongodb-core/lib/cursor.js:433:38)
at self._endSession (/home/user/Documentos/myApi/myServer/node_modules/mongodb-core/lib/cursor.js:441:46)
at Cursor._endSession (/home/user/Documentos/myApi/myServer/node_modules/mongodb-core/lib/cursor.js:195:5)
at Cursor._endSession (/home/user/Documentos/myApi/myServer/node_modules/mongodb/lib/cursor.js:226:59)
at _setCursorNotifiedImpl (/home/user/Documentos/myApi/myServer/node_modules/mongodb-core/lib/cursor.js:441:17)
at setCursorNotified (/home/user/Documentos/myApi/myServer/node_modules/mongodb-core/lib/cursor.js:433:3)
at done (/home/user/Documentos/myApi/myServer/node_modules/mongodb-core/lib/cursor.js:648:16)
at queryCallback (/home/user/Documentos/myApi/myServer/node_modules/mongodb-core/lib/cursor.js:699:18)
at /home/user/Documentos/myApi/myServer/node_modules/mongodb-core/lib/connection/pool.js:532:18
at process._tickCallback (internal/process/next_tick.js:61:11)