es5实现批量的并发请求

假设有一个场景,需要在一个方法里面请求多个接口,并且要在所有的接口都返回了数据之后才能往下面走逻辑。在 es6 里面,我们可以用 promise.all 来实现,但是如果项目是 es5 的话,可能要自己写一下方法了。下面给一个我自己的解决方案:

function multiRequest (requestOptions, callback, finishReq) {
    if (requestOptions.length === 0) {
        return
    }
    var self = this
    var turnRequest = []
    var turnTimes = 0
    var finishTag = []
    
    while(turnRequest.length < 5 && requestOptions.length > 0) {
        turnRequest.push(requestOptions.pop())
        turnTimes += 1
    }
    
    while(turnRequest.length > 0) {
        var httpReq = new window.HttpHelper()
        var reqOpt = turnRequest.pop()
        if (reqOpt.method === 'get') {
            httpReq.get(reqOpt.reqUrl, function (res) {
                finishTag.push(res)
                finishReq.push(res)
                if (finishTag.length === turnTimes) {
                    if ((finishTag.length === 5 && requestOptions.length === 0) || finishTag.length < 5) {
                        callback(finishReq)
                    } else {
                        self.multiRequest(requestOptions, callback, finishReq)
                    }
                }
            })
        } else {
            httpReq.post(
                reqOpt.reqUrl, reqOpt.params,
                { headers: { 'Access-Control-Allow-Origin': '*' } },
                function (res) {
                    finishTag.push(res)
                    finishReq.push(res)
                    if (finishTag.length === turnTimes) {
                        if ((finishTag.length === 5 && requestOptions.length === 0) || finishTag.length < 5) {
                            callback(finishReq)
                        } else {
                            self.multiRequest(requestOptions, callback, finishReq)
                        }
                    }
                }
            )
        }
    }
}

可以这样子调用

this.multiRequest(requestOptions, this.cb, [])

requestOptions 是一个对象数组, cb 是回调函数的引用

[{
            reqUrl: 'http://127.0.0.1:8090/api',
            method: 'get'
}]

函数实现的效果是一起发送 5个请求,等到 5个请求都返回之后再发送 5个请求,这样循环直到 requestOptions 的请求都发送完为止。

上一篇:JavaScript、ES5和ES6的介绍和区别


下一篇:从ES5 的角度看 ES6中的 class