class RequestManager {
    constructor() {
        // 并发请求数
        this.concurrency = 1;
        this.running = 0;
        this.requestQueue = [];
    }

    async pushRequest(request) {
        if (this.running >= this.concurrency) {
            // resolve()未被执行之前，当前request会在这里await
            await new Promise(resolve => this.requestQueue.push(resolve));
        }
        return this._handleRequest(request);
    }

    async _handleRequest(request) {
        this.running++;
        try {
            return await request();
        } catch (error) {
            return Promise.reject(error)
        } finally {
            this.running--;
            if (this.requestQueue.length > 0) {
                // 执行下一个resolve
                this.requestQueue[0]();
                this.requestQueue.shift();
            }
        }
    }
}

export default RequestManager