React Native AsyncStorage getItem返回promise而不是value

Man*_*dan 6 javascript promise react-native asyncstorage

我有一个登录表单,我可以发布我的表单值.在成功发出POST请求后,我从API返回了身份验证令牌.我需要保存此令牌以供将来在某些本地存储中引用.为了保存此身份验证令牌,我使用的是AsyncStorage.我使用AsyncStorage.setItem(STORAGE_KEY, responseData.auth_token);setItem方法来保存数据.

如果我通过控制台登录:

console.log(AsyncStorage.setItem(STORAGE_KEY));

它像这样返回promise对象

    Promise {_45: 0, _81: 0, _65: null, _54: null}
_45
:
0
_54
:
null
_65
:
"efcc06f00eeec0b529b8"
_81
:
1
__proto__
Run Code Online (Sandbox Code Playgroud)

:对象

如何从AsyncStorage.getItem方法中获取确切的值?

这是我的获取方法

fetch('http://54.255.201.241/drivers', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      first_name: this.state.firstName,
      mobile_number: this.state.mobileNumber,
      vehicle_number: this.state.vehicleNumber,
      vehicle_type_id: 1,
    })
  }).then((response) => response.json()).then((responseData) => {
    if (JSON.stringify(responseData.mobile_number) == (this.state.mobileNumber))
    {
      AsyncStorage.setItem(STORAGE_KEY, responseData.auth_token);
      console.log(AsyncStorage.getItem(STORAGE_KEY));
      this.props.navigator.push({id: 'Otp'})
    }
    else
    {
      Alert.alert("SignUp Failed","Mobile number already taken.")  
    }
  })
  .done();
Run Code Online (Sandbox Code Playgroud)

BTW在他们使用的文档等待.我尝试使用它但页面没有加载.在这里附上截图.在此输入图像描述

Abd*_*shi 10

使用Async/Await:

async _getStorageValue(){
  var value = await AsyncStorage.getItem('ITEM_NAME')
  return value
}
Run Code Online (Sandbox Code Playgroud)

  • 这会返回一个 Promise (6认同)

Ank*_*ash 7

你必须打电话给

getUserToken().then(res => {
    console.log(res);
  });
Run Code Online (Sandbox Code Playgroud)

因为这是一个异步调用。

  • 我认为这也应该是正确答案的一部分,因为在我的例子中,我将函数定义为异步,但我在调用中没有使用 then 。 (4认同)