Я новичок в кодировании в ReactNative и JS. Я до сих пор не привык к асинхронной природе javascript. У меня есть функция asyn c, которую я импортирую в свое основное приложение, и внутри вызываю ее внутри componentDidMount. Когда я загружаю приложение в первый раз, оно не выполняется по порядку и возвращает начальные значения. Когда я refre sh, это работает. Я очень признателен, если вы поможете мне решить эту проблему.
Основной код:
import FirebaseStateChange from './App/src/firebase/components/FirebaseStateChange;
export default class App extends React.Component {
gotresult = async () => {
console.log('calling function');
const a = await FirebaseStateChange();
console.log('end of calling function');
};
componentDidMount() {
console.log('comp did mount');
this.gotresult();
console.log('end of did mount');
}
`
Моя асинхронная функция:
let loading = true;
let authenticated = false;
const Thisone = async () => {
firebase.auth().onAuthStateChanged((user) => {
if (user != null) {
if (user.emailVerified === true) {
// this user has signed up and has verified email
loading = false;
authenticated = true;
console.log('1');
console.log(loading);
console.log(authenticated);
} else {
// this user either signedup with fb or hasnt verified email
const providerData = user.providerData[0];
const provID = providerData.providerId;
if (provID === 'facebook.com') {
// fb signedup
loading = false;
authenticated = true;
console.log('2');
console.log(loading);
console.log(authenticated);
} else {
// not verified
loading = false;
authenticated = false;
console.log('3');
console.log(loading);
console.log(authenticated);
}
}
} else {
// this one just opened the page
loading = false;
authenticated = false;
console.log('4');
console.log(loading);
console.log(authenticated);
}
});
};
const FirebaseStateChange = async () => {
try {
const x = await Thisone();
} catch (e) {
console.error('Problem', e);
}
console.log('return line');
console.log(loading);
console.log(authenticated);
return [loading, loading];
};
export default FirebaseStateChange;
Результат - при первой загрузке приложения
comp did mount
calling function
end of did mount
return line
true
false
end of calling function
4
false
false
Результат - обновление кода
comp did mount
calling function
end of did mount
4
false
false
return line
false
false
end of calling function