Created
April 9, 2018 21:32
-
-
Save nmccready/0cd8eea65680c68b42d8763e02a20116 to your computer and use it in GitHub Desktop.
poorman promises (some of bluebird , some of RSVP)
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
import { Promise } from 'es6-promise'; | |
import '../async'; | |
import { map as loMap } from '../../utils/lodash'; | |
import { PromiseTypeError } from '../../errors'; | |
/* keeping bundle size down and shimming Promise utilities as we need them */ | |
if (!Promise.TypeError) { | |
Promise.TypeError = PromiseTypeError; | |
} | |
export function defer() { | |
let resolve, | |
reject; | |
const promise = new Promise((res, rej) => { | |
resolve = res; | |
reject = rej; | |
}); | |
return { | |
fulfill: resolve, | |
resolve, | |
reject, | |
promise | |
}; | |
} | |
if (!Promise.defer) { | |
Promise.defer = defer; | |
} | |
export function tryy(cb) { | |
if (cb == null) { | |
return Promise.reject(new PromiseTypeError('Undefined Function')); | |
} | |
return new Promise((resolve) => { | |
resolve(cb()); | |
}); | |
} | |
if (!Promise.try) { | |
Promise.try = tryy; | |
} | |
if (!Promise.try) { | |
Promise.try = tryy; | |
} | |
export function hash(obj) { | |
const promises = []; | |
let index = 0; | |
const indexToKey = {}; | |
for (const key in obj) { | |
indexToKey[index] = key; | |
promises.push(obj[key]); | |
index += 1; | |
} | |
return Promise.all(promises).then((values) => { | |
const obj = {}; | |
values.forEach((v, i) => { | |
obj[indexToKey[i]] = v; | |
}); | |
return obj; | |
}); | |
} | |
if (!Promise.hash) { | |
Promise.hash = hash; | |
} | |
if (!Promise.props) { | |
Promise.props = hash; | |
} | |
export function join(...args) { | |
if (!args.length) return Promise.resolve([]); | |
if (typeof args[args.length - 1] !== 'function') { | |
return Promise.all(args); | |
} | |
const cb = args.pop(); | |
return Promise.all(args).then(values => cb(...values)); | |
} | |
if (!Promise.join) { | |
Promise.join = join; | |
} | |
export function map(obj, cb) { | |
if (!obj) { | |
return Promise.reject(new Error('Map Object/Array must be defined')); | |
} | |
if (!cb) { | |
return Promise.reject(new Error('Map callback must be defined')); | |
} | |
return Promise.all(loMap(obj, (promise) => { | |
// handle non-promises | |
if (!promise || !promise.then) return cb(promise); | |
return promise.then(cb); | |
})); | |
} | |
if (!Promise.map) { | |
Promise.map = map; | |
} | |
if (typeof global !== 'undefined') { | |
global.Promise = Promise; | |
} | |
export default Promise; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment