exports.index = function(req, res) {
moviedb.indexMovie()
.then(x => {
Movie.findAsync()
.then(responseWithResult(res))
.catch(handleError(res))
}
)
};
function responseWithResult(res, statusCode) {
statusCode = statusCode || 200;
console.log("Populating Response");
return function(entity) {
if (entity) {
res.status(statusCode).json(entity);
}
};
}
The above code works perfectly fine, the returned function in the responsewithresult function, gets populated with the .then response. However, I was experimenting and tried this instead, but it did not work. Please explain why?
exports.index = function(req, res) {
moviedb.indexMovie()
.then(x => {
Movie.findAsync()
.then(x => {responseWithResult(res)}) // <-- this doesn't work
.catch(handleError(res))
})
};
exports.index = function(req, res) {
moviedb.indexMovie()
.then(x => {
Movie.findAsync()
.then(responseWithResult(res))
.catch(handleError(res))
}
)
};
function responseWithResult(res, statusCode) {
statusCode = statusCode || 200;
console.log("Populating Response");
return function(entity) {
if (entity) {
res.status(statusCode).json(entity);
}
};
}
The above code works perfectly fine, the returned function in the responsewithresult function, gets populated with the .then response. However, I was experimenting and tried this instead, but it did not work. Please explain why?
exports.index = function(req, res) {
moviedb.indexMovie()
.then(x => {
Movie.findAsync()
.then(x => {responseWithResult(res)}) // <-- this doesn't work
.catch(handleError(res))
})
};
Share
Improve this question
edited Dec 17, 2015 at 7:52
Amit
46.4k9 gold badges82 silver badges113 bronze badges
asked Dec 17, 2015 at 6:42
shivshiv
3931 gold badge5 silver badges18 bronze badges
2 Answers
Reset to default 3It doesn't work since
.then(responseWithResult(res))
passes the result of responseWithResult
(which is a function that eventually returns a value) to the then
function, whereas
x => {responseWithResult(res)}
which is logically like
function(x) {
responseWithResult(res);
}
and when you put that inside then(...)
, nothing is returned.
You could fix that with
then(x => responseWithResult(res))
which is like
function(x) {
return responseWithResult(res);
}
but really you should refractor your entire function to make better use of promises, and have a cleaner code in the end:
exports.index = function(req, res) {
moviedb.indexMovie()
.then(() => Movie.findAsync())
.then(movie => responseWithResult(movie, res))
.catch(() => handleError(res))
};
function responseWithResult(entity, res, statusCode) {
statusCode = statusCode || 200;
console.log("Populating Response");
res.status(statusCode).json(entity);
}
Because you're returning undefined, add a return
before the responseWithRest
call or remove the {}
s around it to make it an expression arrow function.
Promises work by return value.
Your first example doesn't sequence operations either. The functions get invoked immediately.