gpt4 book ai didi

javascript - 回调随着 set Interval 方法 JavaScript 逐渐增加

转载 作者:行者123 更新时间:2023-11-30 19:10:44 26 4
gpt4 key购买 nike

我正在执行以下脚本和来自 XHR 请求的回调逐渐增加(1、2、3......等),但网络调用只发生一次。

class Service {

profiles = [] //assume array contains objetcs
xhr = new XMLHttpRequest();
token = null;

constructor(token) {
this.xhr = new XMLHttpRequest();
this.token = token
}

setInterval(res => {this.doFunc()}, 10000);

doFunc() {
if (this.profiles.length > 3) {
this.doChoice(this.profiles[0]).then(response => {
console.log(response); //printing only onetime
});
}
}

async doChoice(profile) {
return await new Promise(resolve => {
this.like(profile.id, response => {
//code below is excuting gradually with interval method
console.log('Liked');
console.log(profile);
this.profiles.splice(this.profiles.indexOf(profile), 1);
resolve(JSON.parse(response));
});
})
}

like(id, subscribe = {res: ''}) {
let url = 'https://someurl/' + id;

this.xhr.open("GET", url);
this.xhr.setRequestHeader("x-auth-token", this.token);
this.xhr.addEventListener("readystatechange", function () {
//code below is excuting gradually with interval method
if (this.readyState === 4 && this.status === 200) {
if (this.responseText) {
console.log(this.responseText);
subscribe(this.responseText);
}
}
});
this.xhr.send();
}
}

如果有人能向我解释我在这里做错了什么,那就太棒了!

最佳答案

不要将 XMLHttpRequest 存储为属性。相反,每次您想要/需要向端点发送请求时都创建它。

此外,代码还可以大大简化:

class Service {
constructor(token) {
this.token = token;
this.profiles = [];

setInterval(this.doFunc.bind(this), 10000);
}
doFunc() {
if (this.profiles.length > 3) {
this.doChoice(this.profiles[0]).then(profile => {
console.log('Liked');
console.log(profile);
this.profiles.splice(this.profiles.indexOf(profile), 1);
});
}
}
doChoice(profile) {
return new Promise((resolve, reject) => {
let url = 'https://someurl/' + profile.id;
let xhr = new XMLHttpRequest();

xhr.open("GET", url);
xhr.setRequestHeader("x-auth-token", this.token);
xhr.addEventListener("readystatechange", function () {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(new Error('XMLHttpRequest failed'));
}
});
xhr.send();
});
}
}

正如@HereticMonkey 已经指出的那样,您也不应该在类的方法之外使用 setInterval,因为 (a) 它感觉非常奇怪,并且 (b) 它执行一个副作用(在您的情况下,真的有多个副作用)只需导入类。

关于javascript - 回调随着 set Interval 方法 JavaScript 逐渐增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58505594/

26 4 0
文章推荐: javascript - React,如何访问父级中的子引用
文章推荐: javascript - 在动态 block React 中对父元素使用 ref
文章推荐: javascript - 对象有时无法在 IE 8 中访问
文章推荐: c# - List 到 List C#