【发布时间】:2019-04-24 14:41:48
【问题描述】:
我试图在 React 中按顺序获取多个请求。有3个请求,
- 第一个从后端收集编码信息
- 从认证服务器获取令牌
- 将 api 与令牌一起使用。
所有这些都必须有序。但是由于异步获取功能,我遇到了困难。我无法在 .then() 块之外获得 fetch 的响应。
为了解决这个问题,我使用了 await / async。但它引起了另一个问题。我的 3 个请求必须按顺序排列。当我使用异步时,顺序会被破坏。
这是代码。
class App extends Component {
constructor() {
super();
this.state = { code: '', encoded: '', access_token: '', refresh_token: '' };
}
getCarDetails() {
const carId = '2F3A228F6F66AEA580'
var query = 'https://api.mercedes-benz.com/experimental/connectedvehicle/v1/vehicles/'.concat(carId).concat('/doors')
fetch(query, {
method: 'GET',
headers: {
'Authorization': 'Bearer '.concat(this.state.access_token),
'accept': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
}
getToken() {
var post_data = {
grant_type: 'authorization_code',
code: this.state.code,
redirect_uri: 'http://localhost'
}
fetch('https://api.secure.mercedes-benz.com/oidc10/auth/oauth/v2/token', {
method: 'POST',
headers: new Headers({
'Authorization': 'Basic '.concat(this.state.encoded),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: queryString.stringify(post_data)
})
.then(res => res.json())
.then(data => this.setState({ access_token: data.access_token, refresh_token: data.refresh_token }))
.catch(err => console.log(err));
}
getEncodedClientIdAndClientSecret() {
if (this.state.code != null) {
fetch('http://localhost:8000/encodeClientIdAndSecret', {
method: 'POST'
})
.then(res => res.json())
.then(data => this.setState({ encoded: data.encoded }))
.catch(err => console.log(err));
}
}
componentDidMount() {
const values = queryString.parse(this.props.location.search)
this.setState({ code: values.code })
console.log(this.state)
this.getEncodedClientIdAndClientSecret();
console.log(this.state) //this state is empty
//this.getToken();
//this.getCarDetails();
}
等待/异步
async getEncodedClientIdAndClientSecret() {
if (this.state.code != null) {
const response = await fetch('http://localhost:8000/encodeClientIdAndSecret', {
method: 'POST'
})
const data = await response.json();
console.log(data)
}
}
如果我放置 await / async,我会在 3 个请求之间遇到顺序问题。
【问题讨论】:
-
"我使用了 await / async" - 显示相应的代码。我问它,因为我对“当我使用异步时,顺序被破坏”这句话感到困惑。 Async/await 的顺序没有问题,它不应该被破坏
-
我添加了等待/异步示例@lucifer63
-
首先想到的是你可以在其中使用
async componentDidMount()然后await你的每个函数调用。然而,这可能不是最好的解决方案。 -
谢谢!现在看看:让你所有的 get* 函数异步,然后用 await 调用它们。这样订单就被保留了
标签: javascript promise