在vanilla JavaScript中实现自定义承诺

时间:2017-11-08 12:13:15

标签: javascript asynchronous es6-promise

我尝试使用普通的vanilla JavaScript实现自定义承诺实现。但它不适用于异步然后功能。 如何在代码中进行异步链接?

这是我的代码:

var noop = () => { };

function Promise(callback) {
  callback = callback || noop;
  var thenCallbacks = [];

  this.promisedValue = null;

  this.then = function (callback) {
    callback = callback || noop;
    thenCallbacks.push(callback);
    //this.promisedValue = callback(this.promisedValue) || this.promisedValue;
    return this;
  }

  this.done = function () {
    if (!thenCallbacks.length) {
      debugger;
      return this.promisedValue;
    } else {
      for (var i = 0; i < thenCallbacks.length; i++) {
        this.promisedValue = thenCallbacks[i].call(this, this.promisedValue);
      }
    }
    debugger;
    return this.promisedValue;
  }
  var res = (d) => {
    this.promisedValue = d;
  }

  var rej = (d) => {
    this.promisedValue = d;
  }

  callback.call(this, res, rej);
};

var p = new Promise((res, rej) => {
  res(100);
}).then((d) => {
  console.log('Then 1 called!! ', d);
  return 100233;
}).done();

0 个答案:

没有答案