Reputation: 19
So, this is my index.js in react native projects
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);
Okay, now just focus in getToken function and also a console.log beside that function.
In my mind, when we use async/await the function will return after token variables is done to solve their result, am i right?
But what i get for the output is really confusing for me.. getToken function returning more fast then await AsyncStore value.
This is the output of the code :
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 ------------
Can you see? getToken() function retuning faster than console.log inside the function. How can it run like that?
What i want is, getToken() function returning a string such as "Bearer blablablabla"
Upvotes: 1
Views: 822
Reputation: 8718
You're misunderstanding how async functions work.
When you call an async function, it actually wraps the function body in a Promise which gets returned:
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(...)
If you want your function to wait for a Promise to resolve, it also has to be async and use the await
keyword:
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)
}
I suggest reading this article and similar topics it mentions.
Upvotes: 2