为什么我甚至在.then()
上也无法获得Promise
的值?
.then()
onPress={() => {
onSignIn().then( (_values) => {
alert("_values: " + _values); //undefined
if(_values == 1){
navigation.navigate("SignedIn");
}
})
.catch(error => console.log(error)) //do something in case onSignIn fails
}}
onSignIn()
export const onSignIn = async () => {
if (_values.username && _values.password) {
fetch("http://localhost:3001/sessions/create", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: _values.username,
password: _values.password
})
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.access_token){
AsyncStorage.setItem(USER_KEY, responseData.access_token);
_values.success = 1;
alert("Login successfully!");
//alert("_values.success " + _values.success);
return Promise.resolve(_values.success);
} else if(!responseData.access_token){
alert("Wrong username and password!");
_values.success = 0;
return Promise.resolve(_values.success);
}
});
} else{
alert("Please enter your username and password.");
}
}
_values
export const _values = {
success: ''
};
答案 0 :(得分:5)
因为你没有兑现承诺。
更改
fetch("http://localhost:3001/sessions/create", {
到
return fetch("http://localhost:3001/sessions/create", {