Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript异步函数返回值_Javascript_Async Await_Expo - Fatal编程技术网

JavaScript异步函数返回值

JavaScript异步函数返回值,javascript,async-await,expo,Javascript,Async Await,Expo,我正在为我的本地前端开发AuthService。我从后端获取数据,例如访问令牌,然后将其传递给我的AuthService,并将其存储在expo secure store中。它看起来像这样(authService.js): 在我的组件中,我可以简单地调用以下函数,返回我的用户或jwt: if (auth.getCurrentUser()) { navigation.navigate(routes.NEWS_SCREEN); } 但由于我使用的是expo的secure store,所以

我正在为我的本地前端开发AuthService。我从后端获取数据,例如访问令牌,然后将其传递给我的AuthService,并将其存储在expo secure store中。它看起来像这样(authService.js):

在我的组件中,我可以简单地调用以下函数,返回我的用户或jwt:

if (auth.getCurrentUser()) {
    navigation.navigate(routes.NEWS_SCREEN);
  }
但由于我使用的是expo的secure store,所以我使用了异步函数,例如auth.getCurrentUser()并没有返回我的用户对象,而是返回了一个愚蠢的承诺

我找到了访问数据的解决方案,但前提是我直接在组件内部使用这些函数。这不是我想要的。我需要这样一个AuthService,我可以在几个组件中重用它


我怎样才能解决这个问题?谢谢你们

如果您是从异步函数调用它,您可以像这样使用
wait

const user = await auth.getCurrentUser();
if (user) navigation.navigate(routes.NEWS_SCREEN);
auth.getCurrentUser().then(user => {
  if (user) navigation.navigate(routes.NEWS_SCREEN);
  // continue logic here
});
否则,您可以使用
。然后像这样使用

const user = await auth.getCurrentUser();
if (user) navigation.navigate(routes.NEWS_SCREEN);
auth.getCurrentUser().then(user => {
  if (user) navigation.navigate(routes.NEWS_SCREEN);
  // continue logic here
});
在这两种情况下,
user
将是
getCurrentUser
异步函数中返回的任何内容。

Haha“相反,它返回了一个愚蠢的承诺”。。。我们分享这种情绪的次数