我读到了await
在承诺没有得到解决的情况下停止执行。我正在尝试在我的 React-native 应用程序中执行以下操作:
static async getFromStorage(key) {
const value = await AsyncStorage.getItem(key);
console.log(value);
return value;
}
console.log(Class.getFromStorage("test"));
但我得到以下而不是实际值(Chrome 不允许我复制时间戳......):
- Promise {_45: 0, _81: 0, _65: null, _54: null} <- 这是函数后的console.log
- 100 毫秒后
- REAL_VALUE <- 这是函数中的 console.log
那么为什么我的代码不等待解决承诺呢?
更新
@thedude 建议:
async function waitForStorage() {
console.log(await getFromStorage());
}
waitForStorage();
这个解决方案的问题是我需要在课堂上使用它。但是当我这样做时someVar = await getFromStorage()
,我得到一个 500 错误。我可以等它,因为它是 100 毫秒。
例如:
someVar = await getFromStorage("token");
checkToken(someVar);