我目前在Express Node.js应用程序中定义了一个POST路由,如下所示:
var locationService = require("../app/modules/locationservice.js");
app.post('/createstop', isLoggedIn, function(req, res) {
locationService.createStop(res, req.body);
});(对于这个问题,请假定路由在& db工作。我的记录是在表单提交时创建的,这是我正在努力解决的问题)
在我当前拥有的locationservice.js类中
var models = require('../models');
exports.createStop = function(res, formData) {
models.location.build({ name: formData.name })
.save()
.then(function(locationObj) {
res.json({ dbResult : locationObj });
});
};因此,如您所见,我的路由调用导出函数CreateStop,该函数使用后缀持久层异步插入记录,之后我可以将结果放在承诺的then()中的响应上。
因此,目前只能将响应对象传递到locationservice.js方法中,然后在then()中设置res.json。对于我的服务类来说,这是不太理想的,而且感觉也不太好。
我想要做的是“将”我的createStop方法作为一个允诺/一个回调,这样我就可以返回新的location对象(或一个错误)并在调用方法中处理它--因为这个方法的未来使用可能有一个响应上下文/参数来传递/被填充。
因此,在路线上,我会做更多的事情,比如:
var locationService = require("../app/modules/locationservice.js");
app.post('/createstop', isLoggedIn, function(req, res) {
locationService.createStop(req.body)
.then(dataBack) {
res.json(dataBack);
};
});这意味着,我可以从其他地方调用createStop,并在那个承诺的处理程序中对响应做出反应。但目前我无法理解这一点。我已经做了我的尽职调查研究,但一些个人专家对我的具体情况将是最感谢的意见。
发布于 2017-02-22 13:51:38
你的locationservice.js可能是这样的
exports.createShop = function(data){
// here I have used create instead of build -> save
return models.location.create(data).then(function(location){
// here you return instance of saved location
return location;
});
}然后您的post()方法应该如下所示
app.post('/createstop', isLoggedIn, function(req, res){
locationService.createShop(req.body).then(function(location){
// here you access the location created and saved in createShop function
res.json(location);
}).catch(function(error){
// handle the error
});
});发布于 2017-02-22 13:51:04
用这样的承诺包装您的createStop函数:
exports.createStop = function(res, formData) {
return new Promise(function(resolve, reject) {
models.location.build({ name: formData.name })
.save()
.then(function(locationObj) {
resolve({ dbResult : locationObj });
});
//in case of error, call reject();
});
};这将允许您在路由器内的.then之后使用createStop。
https://stackoverflow.com/questions/42393249
复制相似问题