为什么即使将.then()的值链接到Promise也未定义?

时间:2019-01-02 13:14:54

标签: javascript reactjs react-native

为什么我甚至在.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: ''
};

参考:https://github.com/datomnurdin/auth-reactnative

1 个答案:

答案 0 :(得分:5)

因为你没有兑现承诺。

更改

fetch("http://localhost:3001/sessions/create", {

return fetch("http://localhost:3001/sessions/create", {