【问题标题】:How can i do async/await in AsyncStorage react native?我如何在 AsyncStorage 中进行异步/等待反应本机?
【发布时间】:2021-10-04 10:42:13
【问题描述】:

所以,这是我在 react native 项目中的 index.js

import React, {useEffect} from 'react';
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

import {
  ApolloClient,
  HttpLink,
  ApolloLink,
  InMemoryCache,
  concat,
  ApolloProvider,
} from '@apollo/client';
import {setContext} from '@apollo/client/link/context';
import AsyncStorage from '@react-native-async-storage/async-storage';

const httpLink = new HttpLink({uri: 'https://dev.saba.id/graphql'});

const getToken = async () => {
  const token = await AsyncStorage.getItem('SESSION_TOKEN')
    .then(data => {
      if (data) {
        return data;
      } else {
        return;
      }
    })
    .catch(err => {
      console.log(err);
    });
  console.log('------------');
  console.log('console.log inside getToken function');
  console.log('Bearer ' + token);
  console.log('------------');
  return 'Bearer ' + token;
};

console.log('------------');
console.log('output of getToken function');
console.log(getToken());
console.log('------------');

const headerLink = setContext((request, previousContext) => ({
  headers: {
    // Make sure you include any existing headers!
    ...previousContext.headers,
    authorization: getToken(),
  },
}));

const client = new ApolloClient({
  link: headerLink.concat(httpLink),
  cache: new InMemoryCache(),
});

const Application = () => {
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
};

AppRegistry.registerComponent(appName, () => Application);

好的,现在只关注 getToken 函数以及该函数旁边的 console.log。

在我看来,当我们使用 async/await 时,该函数将在完成令牌变量以解决其结果后返回,对吗?

但是我得到的输出真的让我很困惑.. getToken 函数返回的速度比等待 AsyncStore 值更快。

这是代码的输出:

 BUNDLE  ./index.js 

 LOG  ------------
 LOG  output of getToken function
 LOG  {"_U": 0, "_V": 0, "_W": null, "_X": null}
 LOG  ------------
 LOG  Running "sabaCustomerApp" with {"rootTag":61,"initialProps":{}}
 LOG  ------------
 LOG  console.log inside getToken function
 LOG  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoic2FiYSIsImVtYWlsIjoic2FiYUBnbWFpbC5jb20iLCJyb2xlIjoic3VwZXIgYWRtaW5pc3RyYXRvciIsImlhdCI6MTYyNzQ4ODY1MCwiZXhwIjoxNjMwMDgwNjUwfQ.W3vCNmIxsIyscJBk5aPMN3kqn7EVIEMLfZVgXqHB_UA
 LOG  ------------


你能看到吗? getToken() 函数重新调整比函数内部的 console.log 更快。怎么会这样跑?

我想要的是,getToken() 函数返回一个字符串,例如“Bearer blablablabla”

【问题讨论】:

    标签: javascript react-native asynchronous async-await asyncstorage


    【解决方案1】:

    您误解了异步函数的工作原理。

    当你调用一个异步函数时,它实际上将函数体包装在一个返回的 Promise 中:

    async function test() {
        await ...;
        return 123;
    }
    
    const promise = test();
    console.log(promise); // Promise
    promise.then(result => console.log(result));
    // ^ logs 123 at some point
    console.log('continue'); // runs before .then(...)
    

    如果您希望您的函数等待 Promise 解决,它还必须是异步的并使用 await 关键字:

    function waitSecond() {
        // This function isn't async, but still returns a Promise
        return new Promise(resolve => setTimeout(() => resolve(123), 1000));
    }
    async function otherFunction() {
        console.log(Date.now()); // x
        const result = await waitSecond();
        console.log(result); // 123
        console.log(Date.now()); // x+1000 (roughly)
    }
    

    我建议阅读this article 和它提到的类似主题。

    【讨论】:

    • 感谢您的帮助 Kelvin,但老实说,我仍然对此感到困惑。顺便说一句,我是 react native 和 javascript 的新手。如果你不介意,你能帮我修复我写的代码吗?我真的需要你的帮助..
    • 我不知道 Apollo,所以我不确定如何为其添加异步支持,尤其是因为您似乎需要它同步。也许您可以创建一个异步函数createApolloClient(),并在它仍在加载时,向用户显示一个加载对话框。
    • 我的意思是,你能帮我解决一下 getToken() 的功能吗?所以当我调用 console.log(getToken());代码可以返回结果,例如返回的令牌变量。如果可以的话,我会很感激的
    • @VitoJuliano 我建议阅读我链接的文章。由于getToken() 执行异步操作,您不能只是“调用它并立即获得结果”。调用 getToken() 的代码也必须与 await 异步,或者使用 .then 进行回调。
    • 好的,谢谢你的建议!祝你有美好的一天
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2018-09-21
    • 2019-10-21
    • 1970-01-01
    • 2019-07-02
    • 2021-12-07
    相关资源
    最近更新 更多