我正在使用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);
而且效果也很好。但我现在有两个问题:
我的获取和异步实现是否正确?
如果在这种情况下我不使用await/async,会发生什么?
抱歉,我对 Javascript 中的 Promises 和异步方法有点陌生。谢谢!
最佳答案
async/await
只是 Promise 的语法糖。您已经在使用 Promise,因此无需这样做。只需返回 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
}
}
关于javascript - 如果我在非异步函数中调用 `AsyncStorage.setItem` 而没有等待,会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301350/