Javascript 然后调用匿名函数
Javascript Anonymous function within then call
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);
}
};
}
上面的代码工作得很好,responsewithresult 函数中的返回函数被 .then 响应填充。但是,我正在试验并尝试这样做,但它没有用。请说明原因?
exports.index = function(req, res) {
moviedb.indexMovie()
.then(x => {
Movie.findAsync()
.then(x => {responseWithResult(res)}) // <-- this doesn't work
.catch(handleError(res))
})
};
因为你 return 未定义,所以在 responseWithRest
调用之前添加一个 return
或删除它周围的 {}
使其成为表达式箭头函数.
Promise 按 return 值工作。
您的第一个示例也没有对操作进行排序。这些函数会立即被调用。
从
开始就没用了
.then(responseWithResult(res))
将 responseWithResult
的结果(这是一个最终 returns 一个值的函数)传递给 then
函数,而
x => {responseWithResult(res)}
这在逻辑上类似于
function(x) {
responseWithResult(res);
}
当您将其放入 then(...)
时,不会返回任何内容。
你可以用
解决这个问题
then(x => responseWithResult(res))
这就像
function(x) {
return responseWithResult(res);
}
但实际上您应该重构整个函数以更好地利用 promise,并最终拥有更简洁的代码:
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);
}
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);
}
};
}
上面的代码工作得很好,responsewithresult 函数中的返回函数被 .then 响应填充。但是,我正在试验并尝试这样做,但它没有用。请说明原因?
exports.index = function(req, res) {
moviedb.indexMovie()
.then(x => {
Movie.findAsync()
.then(x => {responseWithResult(res)}) // <-- this doesn't work
.catch(handleError(res))
})
};
因为你 return 未定义,所以在 responseWithRest
调用之前添加一个 return
或删除它周围的 {}
使其成为表达式箭头函数.
Promise 按 return 值工作。
您的第一个示例也没有对操作进行排序。这些函数会立即被调用。
从
开始就没用了.then(responseWithResult(res))
将 responseWithResult
的结果(这是一个最终 returns 一个值的函数)传递给 then
函数,而
x => {responseWithResult(res)}
这在逻辑上类似于
function(x) {
responseWithResult(res);
}
当您将其放入 then(...)
时,不会返回任何内容。
你可以用
解决这个问题then(x => responseWithResult(res))
这就像
function(x) {
return responseWithResult(res);
}
但实际上您应该重构整个函数以更好地利用 promise,并最终拥有更简洁的代码:
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);
}