我正在使用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);
它也能正常工作。但我现在有两个问题:
我的 fetch 和 async 实现是否正确?
如果我在这种情况下不使用 await/async 会发生什么?
抱歉,我对 Javascript 中的 Promise 和异步方法有点陌生。谢谢!
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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句