[英]Expected to return a value in arrow function warning
this pice of code finds a user by id and if is user is not found it creates one but...这段代码通过 id 找到一个用户,如果没有找到用户,它会创建一个但是......
I´m getting the "Expected to return a value in arrow function array-callback-return" warning我收到“预期返回箭头 function array-callback-return 中的值”警告
findUser(id)
.then((user) => {
if (user.empty) {
return createUser()
.then((user) => setUser(user));
} else {
const updatedUser = user.docs[0];
return {
id: updatedUser.id,
...updatedUser.data(),
};
}
})
I can´t get rid of it and I´m not sure why is happening.我无法摆脱它,我不确定为什么会这样。 thanks.谢谢。 hope this piece of code helps you don´t want to see it all: is a mess :)希望这段代码能帮助你不想看到这一切:一团糟 :)
The problem is that you're not consistently returning a value from inside findUser
's .then
.问题是您没有始终如一地从findUser
的.then
中返回一个值。 You should return the createUser
call:您应该返回createUser
调用:
if (user.empty) {
return createUser()
.then
This is useful because it means that the resulting Promise chain will resolve when createUser
and setUser
finish.这很有用,因为这意味着生成的 Promise 链将在createUser
和setUser
完成时解析。 Otherwise, the createUser
/ setUser
Promise will be disconnected from the outside - you won't be able to determine when it finishes, or handle its errors.否则, createUser
/ setUser
Promise 将与外部断开连接——您将无法确定它何时完成或处理它的错误。
Note that you don't need an anonymous callback which calls setUser
- you can pass the setUser
function itself to the .then
:请注意,您不需要调用setUser
的匿名回调 - 您可以将setUser
function 本身传递给.then
:
return createUser()
.then(setUser);
You also might consider using async
/ await
, the control flow will be clearer:你也可以考虑使用async
/ await
,控制流程会更清晰:
const user = await findUser(id);
if (user.empty) {
const createdUser = await createUser();
// no need to await below if setUser doesn't return a Promise
await setUser(user);
} else {
const updatedUser = user.docs[0];
return {
id: updatedUser.id,
...updatedUser.data(),
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.