在用function本机编写应用程序时,我遇到了与承诺相关的某些障碍,因此我有一个负责授权请求的函数。
export const authorizeRequest = async () => {
const token = await deviceStorage.getItem('accessToken');
return axios.create({
timeout: 2000,
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
}
});
};为了从其中获取数据,我用样式编写了代码。
authorizeRequest().then(a => a.get('http://192.168.0.60:8080/users/echo2/asd')
.then(response => ToastAndroid.show('Response ' + response.data, ToastAndroid.SHORT))
.catch(error => ToastAndroid.show('error ' + JSON.stringify(error), ToastAndroid.LONG)))是否可以避免在调用.then时第一次使用authorizeRequest().then(....),从而使查询看起来像authorizeRequest().get('xxx').then(xxx).catch(xxx),谢谢!
发布于 2019-03-10 20:34:01
当您已经使用promise语法将您的值从设备存储中取出时,为什么要使用async/await语法?
您可以使用async/await重写代码,这样可以更容易地查看代码中正在发生的事情。
export const authorizeRequest = async (url) => {
try {
const token = await deviceStorage.getItem('accessToken');
const a = await axios.create({
timeout: 2000,
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
}
});
const response = a.get(url);
ToastAndroid.show('Response ' + response.data, ToastAndroid.SHORT);
// return response.data // <- you could return something here
} catch (error) {
ToastAndroid.show('error ' + JSON.stringify(error), ToastAndroid.LONG);
}
};以上述方式编写代码意味着可以避免承诺链接。
然后,您可以以下列方式使用它:
await authorizeRequest('http://192.168.0.60:8080/users/echo2/asd')如果您想从authorizeRequest函数中获得一个值,您只需返回response.data,然后按如下方式访问它:
const data = authorizeRequest('http://192.168.0.60:8080/users/echo2/asd')下面是一些关于promises和async/await的优秀文章。
https://stackoverflow.com/questions/55089731
复制相似问题