Skip to content

Instantly share code, notes, and snippets.

@Rafe
Created January 12, 2021 13:57
Show Gist options
  • Save Rafe/5c4ad3e241006372cd6f8ad90a3122cc to your computer and use it in GitHub Desktop.
Save Rafe/5c4ad3e241006372cd6f8ad90a3122cc to your computer and use it in GitHub Desktop.
const Unitialized = -1;
const Pending = 0;
const Resolved = 1;
const Rejected = 2;
function lazy(ctor) {
// hold component state in closure
const payload = {
_status: Unitialized,
_result: ctor
}
return {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer
}
}
function lazyInitalizer(payload) {
// import when first initialize
if (payload._status === Uninitialized) {
const thenable = payload._result();
// Transition to the Pending state.
payload._status = Pending,
payload._result = thenable
thenable.then(
// save result to payload
moduleObject => {
if (payload._status === Pending) {
// Transition to the Resolved state.
payload._status = Resolved
payload._result = moduleObject.default
}
},
error => {
if (payload._status === Pending) {
// Transition to the Rejected state.
payload._status = Rejected;
payload._result = error;
}
},
);
} else if (payload._status === Resolved) {
// return result when resolved.
return payload._result;
} else {
// throw Promise or Error when status is Pending or Rejected.
throw payload._result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment