Skip to content

Instantly share code, notes, and snippets.

@yongjun21
Last active May 17, 2019 07:37
Show Gist options
  • Save yongjun21/8d3a2873506524b13ee0c7e630eef88b to your computer and use it in GitHub Desktop.
Save yongjun21/8d3a2873506524b13ee0c7e630eef88b to your computer and use it in GitHub Desktop.
Light weight Promise polyfill
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