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

问题描述 投票:0回答:1

我正在使用fetch方法从服务器获取一些数据。一旦我获得了这些数据,我需要在AsyncStorage中存储一些数据(access_token更准确,因为我使用的是oauth)。我试着在没有等待的情况下做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和Asynchronous方法的新手。谢谢!

javascript react-native asynchronous promise
1个回答
3
投票

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
});

回复评论中的问题

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
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.