我正在使用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);
它也很好用。但是我现在有两个问题:
我的提取和异步实现正确吗?
如果在这种情况下不使用await / async,会发生什么?
对不起,我对Java语言中的Promises和Asynchronous方法有点陌生。谢谢!
答案 0 :(得分:3)
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
});
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
}
}