【发布时间】:2019-11-18 07:08:01
【问题描述】:
你好,在设置了一个简单的异步函数后,我想使用 promise return 而不是 try! 但正在回归
await 是保留字
函数中的第二个等待。
我已经尝试将异步返回承诺数据!但也没有用
async infiniteNotification(page = 1) {
let page = this.state.page;
console.log("^^^^^", page);
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch(`/notifications?page=${page}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
params: { page }
})
.then(data => data.json())
.then(data => {
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch("/notifications/mark_as_read", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
body: JSON.stringify({
notification: {
read: true
}
})
}).then(response => {
this.props.changeNotifications();
});
})
.catch(err => {
console.log(err);
});
}
> await 是保留字 (100:25) 让 auth_token = 等待 AsyncStorage.getItem(AUTH_TOKEN); ^ fetch("/notifications/mark_as_read", {
【问题讨论】:
-
你的内部函数不是异步的。我会避免使用
.then -
为什么要混合使用 async await 和 promise.then?这看起来是一个进行一些重构的好地方,使您的请求成为单独的函数,等待那些您可以删除承诺的方法。然后回调
-
.then(async (data) => {。您可以定义内联异步回调。 -
这是一个链接,所以这里有更多上下文:)
-
好的! @JohnRuddell,非常感谢你!并感谢您对重构和代码示例的回答!
标签: javascript reactjs react-native async-await