简体   繁体   中英

How waiting async return in a sync function

I'm working on a react native app, in App.js before my App function I fetch my token in the AsyncStorage and in the App function I check if this token exist or if he's not expired. But to get informations in AsyncStorage use Async function and my App function can't be async. The App function will be call later by react native, so I can't use 'then' and callback.

let token;
let expirationDate;
AsyncStorage.getItem('accessToken').then((response) => token = response)
AsyncStorage.getItem('expirationTokenDate').then((response) => expirationDate = response)

const App = () => {
    if (!token | !expirationDate | expirationDate < Date.now()) {
        //return something
    }
    //return another thing
}

export default App;

Turn your variables into state ie:

const [token, setToken] = useState(null);
const [expirationTokenDate, setExpirationTokenDate] = useState(null);

AsyncStorage.getItem('accessToken').then((response) => setToken(response.data)
AsyncStorage.getItem('expirationTokenDate').then((response) => setExpirationTokenDate(response.data)

const App = () => {
    if (!token | !expirationDate | expirationDate < Date.now()) {
        //return something
    }
    //return another thing
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM