我有一个简单的输入形式,在其中放置了一个字符串列表,然后对于字符串(string [i])的每个元素,我向api运行ajax Get请求。 所以这是ajax请求:
async function getUsers(props){
try{
const response = await Axios.get(`url=`+props)
console.log(response)
return response;
}catch{
console.log("response failed")
}
}
我在这里运行它:
... some code here ...
for(var i =0; i < string.length; i++){ // map the entery (string)
getUsers(string[i]).then(res => {
this.setState({
string2:res // this one is just for testing
});
console.log(res.data.id);
mystring22.push({res});
console.log("me inside the promise : " + this.state.string2.data.id);
})
setTimeout(() => {
console.log("iam not empty " + this.state.string2.data.id);
console.log(mystring22);
/* -----------------
I WANT TO DO SOME WORK HERE
-----------------*/
}, 3000);
this.setState({
string3 : mystring22
})
... some code here ...
所以一切正常,而我的问题是: 代码花费太多时间(每个请求3秒钟),有没有一种方法可以更改代码,因此它可以在每个请求之后执行“ SOMETHING”,我试图删除setTimeout或减少它,但是无法正常工作此后未定义。 希望您能够帮助我 。 谢谢
答案 0 :(得分:0)
setState
是一个异步函数,因此在您调用时:
setState({ string2: res });
this.state.string2; // OUTDATED
为了访问更新后的值,必须使用回调:
setState({ string2: res },
() => { console.log(this.state.string2) }); // UP TO DATE
在此codesandbox example,with the callback on line 27和without the callback on 33中可以看到。