Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【并行及串行请求处理】 #64

Open
kind-hearted opened this issue Oct 30, 2018 · 0 comments
Open

【并行及串行请求处理】 #64

kind-hearted opened this issue Oct 30, 2018 · 0 comments

Comments

@kind-hearted
Copy link
Owner

kind-hearted commented Oct 30, 2018

// 处理并行请求, 必须是两个以上的请求
function Parallel(parallels) {
  this._parallels = parallels || [];
  this._return = this;
  this._result = '';
  this._status = '';
  this._resolve = function () {};
  this._reject = function () {};
}

Parallel.prototype.resolve = function (result) {
  this._result = result;
  this._status = 'resolve';

  var flag = true;
  var results = [];
  var parallels = this._return._parallels;

  for (var i = 0, len = parallels.length; i < len; i++) {
    if (parallels[i]._status !== 'resolve') {
      flag = false;
    }

    results.push(parallels[i]._result);
  }

  if (flag) {
    this._return._resolve(results);
  }
};

Parallel.prototype.reject = function (result) {
  this._result = result;
  this._status = 'reject';
  this._return._status = 'reject';
  this._return._reject(result);
};

Parallel.prototype.wait = function (resolve, reject) {
  this._resolve = resolve;
  this._reject = reject;
};

Parallel.all = function (parallels) {
  var parallel = new Parallel(parallels);

  for (var i = 0, len = parallels.length; i < len; i++) {
    parallels[i]._return = parallel;
  }

  return parallel;
};
// 处理串行请求
function Serial(resolve, reject) {
  this._next = null;
  this._resolve = resolve;
  this._reject = reject;
}

Serial.prototype.resolve = function (result) {
  if (this._next) {
    this._next._resolve(result);
  }
};

Serial.prototype.reject = function (reason) {
  // 循环到catch
  this._next._reject(result);
};

Serial.prototype.next = function (serial) {
  this._next = serial;
};
var resolve = function (result) {
  var that = this;

  setTimeout(function () {
    that.resolve(result + '链 ');
  }, 2000);
};
var serial1 = new Serial(resolve);
var serial2 = new Serial(resolve);
var serial3 = new Serial(resolve);
var serial4 = new Serial(function (result) {
  console.log(result);
});

serial1.next(serial2);
serial2.next(serial3);
serial3.next(serial4);

serial1.resolve('开始');
@kind-hearted kind-hearted changed the title 【并行请求处理】 【并行及串行请求处理】 Oct 31, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant