doSetTimeout = (value, timer) => {
setTimeout(() => {
value
}, timer);
}
在此处致电doSetTimeout:
let Data = [
{"name":"John","age":"25"},
{"name":"Alex","age":"31"},
{"name":"Rose","age":"18"},
]
sendData = () => {
for(let i=0; i<Data.length; i++) {
doSetTimeout(
()=> {
var myHeaders = new Headers();
myHeaders.append("token", this.state.Token);
myHeaders.append("Content-Type", "application/json");
let Data = JSON.stringify(Data[i]);
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: Data,
redirect: 'follow'
};
fetch(sycnAddress + "Data", requestOptions)
.then(response => response.json())
.then((responseJson) => {
console.log(responseJson);
return responseJson;
})
.catch((error) => {
console.log(error);
});
}
, i*3000);
}
}
我希望以3秒的间隔将数据一一发送到服务器 但是此功能有问题,无法发送数据!
答案 0 :(得分:0)
尝试在内部使用闭包单例函数
let Data = [
{"name":"John","age":"25"},
{"name":"Alex","age":"31"},
{"name":"Rose","age":"18"},
]
sendData = () => {
for(let i=0; i<Data.length; i++) {
(function(indx){
setTimeout(function(){
var myHeaders = new Headers();
myHeaders.append("token", this.state.Token);
myHeaders.append("Content-Type", "application/json");
let Data = JSON.stringify(Data[i]);
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: Data,
redirect: 'follow'
};
fetch(sycnAddress + "Data", requestOptions)
.then(response => response.json())
.then((responseJson) => {
console.log(responseJson);
return responseJson;
})
.catch((error) => {
console.log(error);
});
}, 3000 * indx);
}(i));
}
}