如何解决如何在此处解决nodeJS中的并发请求问题?
在节点课程中,讲师实现一个称为promisequeue的类来一次处理特定数量的请求,这是该类
class PromiseQueue{
constructor(promises = [],num = 1){
this.concurrent = num;
this.total = promises.length;
this.todo = promises;
this.running = [];
this.complete = [];
}
graphTasks(){
var {todo,running,complete} = this;
logUpdate(`
todo=${todo.map(toX)}
running=${running.map(toX)}
complete=${complete.map(toX)}
`)
}
get runAnother(){
return this.running.length < this.concurrent && this.todo.length > 0
}
run(){
while(this.runAnother){
const promise = this.todo.shift();
this.running.push(promise)
promise.then(() => {
this.complete.push(this.running.shift())
this.graphTasks();
this.run();
})
this.graphTasks()
}
}
}
我的问题是:假设我们一次向此添加2个诺言。运行然后第二个诺言首先解决,但在这一行
this.complete.push(this.running.shift())
它将向this.complete添加第一个承诺,尽管尚未解决 这是一个错误还是我错过了什么
解决方法
我知道了。 如果第二个诺言首先得到解决,则第一个诺言将在仍然运行的情况下达到this.complete,而第三个诺言将添加到this.running中。 因此,我们仍然在this.complete中运行一个,在this.running中运行一个,这保证了我们一次只有2个。 感谢您尝试解决的任何人
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。