如果我在非异步函数中调用 `AsyncStorage.setItem` 而没有 await 会发生什么?

goo*_*ing 0 javascript asynchronous promise react-native

我正在使用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);
Run Code Online (Sandbox Code Playgroud)

它也能正常工作。但我现在有两个问题:

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

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

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

Jar*_*ith 5

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

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
});
Run Code Online (Sandbox Code Playgroud)

在评论中回答问题

上面的 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
  }
}
Run Code Online (Sandbox Code Playgroud)