>  기사  >  웹 프론트엔드  >  es6-promise 소스 코드 분석

es6-promise 소스 코드 분석

不言
不言앞으로
2019-03-23 10:03:182764검색

이 기사의 내용은 es6-promise 소스 코드 분석에 관한 것입니다. 이는 특정 참조 가치가 있으므로 도움이 필요한 친구에게 도움이 되기를 바랍니다.

주요 로직:

본질적으로는 여전히 콜백 함수입니다.
_구독자의 판단을 통해 비동기식과 동기식의 구분을 완성합니다.
then 체인의 흐름은 해결, 거부 -> 게시 -> 호출Callback -> 해결, 거부를 통해 완료되며 다음 then의 상위는 이전의 하위입니다.

동기화 중인 함수 흐름 : 생성자 -> 리졸버 -> 공개 -> 호출Callback
생성자 -> 리졸버 -> 호출Callback

1 생성자의 역할

: 리졸버에 리졸브 바인딩 -

constructor(resolver) {
    this[PROMISE_ID] = nextId();
    this._result = this._state = undefined;
    this._subscribers = [];
    <!-- 判断resolver是不是一个空对象 -->
    if (noop !== resolver) {
      typeof resolver !== 'function' && needsResolver();
      <!-- 把resolve,reject绑定到 resolver上-->
      this instanceof Promise ? initializePromise(this, resolver) : needsNew();
    }
  }

2 then

기능: 콜백 함수를 _subscribers에 바인딩하고 마지막으로 then에 대한 구문 설탕입니다 _subscribers의 매개변수는 배열입니다. [0] 그의 자식이며 다음 then 체인의 상위에 바인딩되어 재귀 호출을 게시하는 데 사용됩니다. 두 번째는 해결 콜백이고 세 번째는 거부 콜백

export default function then(onFulfillment, onRejection) {
  const parent = this;
  <!-- 用于then链的返回值,下一条then就是当前parent的child -->
  const child = new this.constructor(noop);

  if (child[PROMISE_ID] === undefined) {
    makePromise(child);
  }

  const { _state } = parent;
 <!-- 判断_state的状态,是不是PENDING -->
  if (_state) {
    const callback = arguments[_state - 1];
    asap(() => invokeCallback(_state, child, callback, parent._result));
  } else {
    subscribe(parent, child, onFulfillment, onRejection);
  }

  return child;
}

3 게시

함수입니다. 해결하면 거부 트리거가 게시라고 불리고 게시는 계속해서 호출 콜백을 호출하고 반환 값을 통해 계속해서 해결 및 거부를 호출하여 재귀를 형성하여 then 체인의 흐름을 완료합니다

function publish(promise) {
  let subscribers = promise._subscribers;
  let settled = promise._state;

  if (subscribers.length === 0) { return; }

  let child, callback, detail = promise._result;

  for (let i = 0; i < subscribers.length; i += 3) {
    child = subscribers[i];
    callback = subscribers[i + settled];

    if (child) {
      invokeCallback(settled, child, callback, detail);
    } else {
      callback(detail);
    }
  }

  promise._subscribers.length = 0;
}

tip:

마지막으로 콜백

return promise.then(value => constructor.resolve(callback()).then(() => value),
                         reason => constructor.resolve(callback()).then(() => { throw reason; }));

이 기사에 따르면 반환 매개변수가 없습니다. 더 흥미로운 내용을 보려면 PHP 중국어 웹사이트의 JavaScript Video Tutorial

열을 참조하세요.

위 내용은 es6-promise 소스 코드 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제