首页 > 解决方案 > 我如何在 AsyncStorage 中进行异步/等待反应本机?

问题描述

所以,这是我在 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”

标签: javascriptreact-nativeasynchronousasync-awaitasyncstorage

解决方案


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

当您调用异步函数时,它实际上将函数体包装在一个返回的 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)
}

我建议阅读这篇文章和它提到的类似主题。


推荐阅读