我有一个有效的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}
我做错了什么?
答案 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;
}