【问题标题】:What might happen if I call `AsyncStorage.setItem` without await in non async function?如果我在非异步函数中不等待就调用“AsyncStorage.setItem”会发生什么?
【发布时间】:2018-09-12 18:24:44
【问题描述】:

我正在使用fetch 方法从服务器获取一些数据。获得该数据后,我需要将其中的一些数据(更准确地说是 access_token,因为我使用的是 oauth)存储在 AsyncStorage 中。我试着在没有等待的情况下只做AsyncStorage.setItem,而不是在https://facebook.github.io/react-native/docs/asyncstorage 中显示它,它工作得很好。

我改成:

fetch ('site/login', POST ...)
.then((response) => response.json())
.then(async(responseJson) => {
   if (user.valid)
    await AsyncStorage.setItem('access_token', responseJson.token);

而且它也可以正常工作。但我现在有 2 个问题:

我的 fetch 和 async 实现是否正确?

如果我在这种情况下不使用 await/async 会发生什么?

抱歉,我对 Javascript 中的 Promises 和异步方法有点陌生。谢谢!

【问题讨论】:

  • 你上面提到的实现是对的。如果在这种情况下不使用 await/async,则会得到 Promise 子句的结果。
  • 一条建议:阅读有关 Promise 的内容,尤其是有关链接它们的内容(.then() 可能返回另一个 Promise 或非 Promise 结果,并且处理方式有所不同)。这也有助于理解async/await 是如何在幕后工作的。 p.s.这将更好地解释为什么在链式.then 中不需要 async/await,正如 Jared Smith 所演示的那样。 pps Promise 真的很有趣
  • 好吧,如果您不想等待,可以just fire and forget it。但是通常你的调用者可能会期望在你的函数完成之后令牌被保存在存储中,并且依赖于它的代码可能会中断。

标签: javascript react-native asynchronous promise


【解决方案1】:

async/await 只是 Promises 的语法糖。你已经在使用 Promises,所以没有必要这样做。只需返回 Promise:

fetch ('site/login', POST ...)
.then((response) => response.json())
.then((responseJson) => {
  if (user.valid) { // not sure where 'user' came from, but whatever
    return AsyncStorage.setItem('access_token', responseJson.token);
  } else {
    throw new Error('Invalid user');
  }
})
.then(_ => { // storage set, don't care about return value
  // do stuff
})
.catch((err) => {
  // handle error, including invalid user
});

在 cmets 中对问题的回应

async/await 中的上述内容如下所示:

async function foo() {
  try {
    const response = await fetch('site/login', POST ...);
    const responseJson = await response.json();
    if (user.valid) {
      return await AsyncStorage.setItem('access_token', responseJson.token);
    } else {
      throw new Error('Invalid user');
    }
  } catch (error) {
    // deal with errors
  }
}

【讨论】:

  • 非常感谢!如果我不使用 Promises 会怎样?如果没有等待,它不会工作吗?
  • @good_evening 更新了我的答案。您别无选择,只能使用 Promises,因为这是 fetchresponse.json() 等返回的内容,但您可以使用 async/await 来完善它们。但它仍然是 Promise,foo 总是会返回一个 Promise。
猜你喜欢
  • 2020-07-09
  • 2019-12-04
  • 2018-12-28
  • 1970-01-01
  • 2016-01-10
  • 2019-04-29
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多