gpt4 book ai didi

然后调用Javascript匿名函数

转载 作者:行者123 更新时间:2023-11-29 16:08:40 25 4
gpt4 key购买 nike

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))
})
};

最佳答案

它不起作用,因为

.then(responseWithResult(res))

responseWithResult 的结果(这是一个最终返回值的函数)传递给 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);
}

关于然后调用Javascript匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34328190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com