gpt4 book ai didi

javascript - es6 js promise : What is . catch(callback) 相当于?

转载 作者:行者123 更新时间:2023-11-28 04:30:54 25 4
gpt4 key购买 nike

所以我在下面有这个小代码

router.param('username', function (req, res, next, username)
{
User.findOne({username: username}).then(function (user)
{
if (!user)
{
return res.sendStatus(404);
}

req.profile = user;

return next();
}).catch(next);
});

我的问题是这部分.catch(next)

它实际上会做什么?它基本上会调用 next() 回调吗?它将任何错误传递到该回调中,即 next(error) 吗?或者它会以不同的方式调用它,例如 next(null, error) ?

我正在尝试将上面的代码转换为 async/await,那么下面的代码会执行与上面的代码完全相同的操作吗?

router.param('username', async function (req, res, next, username)
{
try
{
let user = await User.findOne({username: username});

if (!user)
{
return res.sendStatus(404);
}

req.profile = user;

return next();
}
catch(error)
{
next(error);
}
});

最佳答案

What is .catch(callback) equivalent to?

它相当于.then(null,callback)。或者您可能正在考虑 eta conversion ,在这种情况下,它也相当于 .catch(err => next(err))

What will it actually do? Will it basically call the next() callback?

是的,这就是回调的工作原理。

Will it pass any error into that callback i.e. next(error)?

是的,当 promise 因该错误而被拒绝时。

Or will it call it in a different way such as next(null, error)?

不,为什么会这样?

I am trying to convert the above code to async/await, will my attempt do the exact same thing?

是的,就 .catch 而言,假设 next 不返回任何内容。

关于javascript - es6 js promise : What is . catch(callback) 相当于?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44618669/

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