簡體   English   中英

如何在此處解決 nodeJS 中的並發請求問題?

[英]How can I fix the concurrent requests issue in nodeJS here?

在節點課程中,講師實現了一個名為 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()
            }
        }
    }

我的問題是:假設我們一次向 this.running 添加 2 個承諾,然后第二個承諾首先解決,但在這一行

this.complete.push(this.running.shift())

它會將第一個承諾添加到 this.complete 雖然它還沒有解決這是一個錯誤還是我錯過了什么

我已經想通了。 如果第二個promise先解決,第一個promise將在仍在運行時執行this.complete,而第三個promise將添加到this.running。 所以我們有一個仍在 this.complete 中運行,一個在 this.running 中,這保證我們一次只有 2 個。 感謝任何人試圖解決

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM