Last active
May 17, 2019 07:37
-
-
Save yongjun21/8d3a2873506524b13ee0c7e630eef88b to your computer and use it in GitHub Desktop.
Light weight Promise polyfill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Promise = window.Promise || (function () { | |
function PromiseLike (init) { | |
let state = 'pending' | |
let resolved, error | |
const pendingResolve = [] | |
const pendingReject = [] | |
function resolve (value) { | |
state = 'resolved' | |
resolved = value | |
pendingResolve.forEach(function (fn) { fn(value) }) | |
} | |
function reject (err) { | |
state = 'rejected' | |
error = err | |
pendingReject.forEach(function (fn) { fn(err) }) | |
} | |
init(resolve, reject) | |
return { | |
then: function (onResolve) { | |
if (state === 'rejected') return this | |
return PromiseLike(function (resolve, reject) { | |
const wrappedOnResolve = wrapPending(onResolve, resolve, reject) | |
if (state === 'resolved') wrappedOnResolve(resolved) | |
else pendingResolve.push(wrappedOnResolve) | |
}) | |
}, | |
catch: function (onReject) { | |
if (state === 'resolved') return this | |
return PromiseLike(function (resolve, reject) { | |
const wrappedOnReject = wrapPending(onReject, resolve, reject) | |
if (state === 'rejected') wrappedOnReject(error) | |
else pendingReject.push(wrappedOnReject) | |
}) | |
} | |
} | |
} | |
function wrapPending (pending, onResolve, onReject) { | |
return function (value) { | |
try { | |
const pendingResolved = pending(value) | |
if (pendingResolved && pendingResolved.then) { | |
pendingResolved.then(function (value) { onResolve(value) }) | |
.catch(function (err) { onReject(err) }) | |
} else { | |
onResolve(pendingResolved) | |
} | |
} catch (err) { | |
onReject(err) | |
} | |
} | |
} | |
PromiseLike.resolve = function (value) { | |
return PromiseLike(function (resolve) { resolve(value) }) | |
} | |
PromiseLike.reject = function (err) { | |
return PromiseLike(function (resolve, reject) { reject(err) }) | |
} | |
return PromiseLike | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment