React Native:返回AsyncStorage.getItem()在函数中获取的值

时间:2016-10-13 18:41:40

标签: react-native

我有一个有效的OrderHistory模型:

import { AsyncStorage } from 'react-native';

const tokenKey = "orderHistory";

export default class OrderHistory extends Object {
  static ordersPlaced() {
    return AsyncStorage.getItem(tokenKey);
  }
}

在我的组件中我有这个:

  showConfirmOrderModal() {
    alert("booya");
  }

  onBuyButtonPress() {
    OrderHistory.ordersPlaced().then((amount) => {
      switch(amount) {
        case null:
          this.showConfirmOrderModal();
          break;
        default:
          this.addToCart(this.state.currentOrder);
      }
    });
  }

有没有办法移动.then函数来解析OrderHistory模型中AsyncStorage.getItem()返回的Promise?我试过这样的事情,但它没有工作:

orderhistory:

export default class OrderHistory extends Object {
  static async ordersPlaced() {
    AsyncStorage.setItem("myKey", "My value here");
    return AsyncStorage.getItem("myKey").then((value) => value);
  }
}

成分:

  onBuyButtonPress() {
    let blah = OrderHistory.ordersPlaced();
    console.log(blah);
  }

但是打印Promise {_45: 0, _81: 0, _65: null, _54: null}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

AsyncStorage方法返回您需要处理的Promise。为了使它更好并摆脱.then回调地狱,你可以使用async/await语法仍然需要Promise并“等待”它的完成:

static async ordersPlaced() {
  await AsyncStorage.setItem("myKey", "My value here");
  const value = await AsyncStorage.getItem("myKey");
  //check your value, process it, etc.
  return value;
}