ES6异步承诺

时间:2016-10-22 20:09:38

标签: javascript ecmascript-6 es6-promise

我仍然是ES6的初学者。 我试图创建一个函数,该函数发送一个http(s)请求,其中包含一个发送http(s)请求的逻辑。如果有5个或更多正在进行的请求,则必须等到1个 完成后,您可以处理下一个请求。 当响应代码不是200时,您需要重试3次。如果响应代码之后 重试3次仍然不是200,那么应该执行错误功能。 我也希望接收响应体的JSON数据作为函数参数。

function httpGet(url) {
    return new Promise(
        function (resolve, reject) {
            const request = new XMLHttpRequest();
            request.onload = function () {
                if (this.status === 200) {
                    // Success
                    resolve(this.response);
                } else {
                    // Something went wrong (404 etc.)
                    reject(new Error(this.statusText));
                }
            };
            request.onerror = function () {
                reject(new Error(
                    'XMLHttpRequest Error: '+this.statusText));
            };
            request.open('GET', url);
            request.send();
        });
}

这是我到目前为止所做的。 谢谢

1 个答案:

答案 0 :(得分:3)

这是承诺回调的一般队列:

// Helper to run a callback when a promise either resolves, or rejects.
function fin(promise, callback){
  return promise.then(
    value => (callback(), Promise.resolve(value)),
    error => (callback(), Promise.reject(error))
  );
}

function makeQueue(maxParallel){
  const queue = [];
  let inProgress = 0;

  // Run the oldest queued task.
  function run(){
    const {resolve, reject, callback} = queue.shift();

    inProgress++;
    return fin(callback(), () => inProgress--).then(resolve, reject);
  }

  // If more tasks can run in parallel, start them
  function dequeue(){
    if (queue.length > 0 && inProgress < maxParallel) run().then(dequeue);
  }

  return function(callback){
    return new Promise((resolve, reject) => {
      queue.push({resolve, reject, callback});
      dequeue();
    });
  }
}

然后使用队列对httpGet进行排队:

const queue = makeQueue(5);

// Queue up httpGet calls.
function httpGetWithQueue(url){
  return queue(() => httpGet(url));
}

然后用重试逻辑调用它:

// Call httpGet with queued processing, with the request tried
// up to three times.
function httpGetWithRetry(url){
  let result = Promise.reject();

  for (var i = 0; i < 3; i++){
    result = result.catch(() => httpGetWithQueue(url));
  }
  return result;
}