-3

我读到了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);
4

1 回答 1

1

运行的代码console.log也应该被标记为async,它也应该await是返回值getFromStorage

例如,这会起作用:

async function waitForStorage() {
   console.log(await getFromStorage());
}
waitForStorage(); // now the console messages should be in the correct order

或者您可以等待承诺的解决方案:

getFromStorage("token").then(someVar => checkToken(someVar))
于 2017-04-18T14:52:11.997 回答