Open tunnckoCore opened 8 years ago
something for promisify everything
'use strict'
var co = require('co')
var pify = require('pify')
var isGenFn = require('is-es6-generator-function')
var isPromise = require('is-promise')
var thenCallback = require('then-callback')
var isNodeStream = require('is-node-stream')
var isChildProcess = require('is-child-process')
var tryCatchCore = require('try-catch-core')
var handleStream = require('handle-stream')
var handleObservable = require('handle-observable')
function relike (val, opts, done) {
if (typeof opts === 'function') {
done = opts
opts = null
}
if (typeof val !== 'function') {
var fn = function wrapper () {
return val
}
val = fn
}
val = isGenFn(val) ? co.wrap(val) : val
tryCatchCore(val, opts, function (err, res) {
if (err) return done(opts.Promise.reject(err))
if (res instanceof Error) return done(opts.Promise.reject(res))
if (isNodeStream(res) || isChildProcess(res) {
res = pify(handleStream, opts)(res)
}
if (isObservable(res)) {
res = pify(handleObservable, opts)(res)
}
if (!isPromise(res)) {
res = opts.Promise.resolve(res)
}
thenCallback(res).then(done)
})
}
function isObservable (val) {
return val && typeof val === 'object' && typeof val.subscribe === 'function'
}
pify(relike)(123).then(console.log) // => 123
pify(relike)(() => 333).then(console.log) // => 333
pify(relike)(() => Promise.resolve(44)).then(console.log) // => 44
pify(relike)(function * () {
return 111
}).then(console.log) // => 111
pify(relike)(function * () {
return Promise.resolve(55)
}).then(console.log) // => 55
pify(relike)(function * () {
yield Promise.resolve('foo')
}).then(console.log) // => 'foo'
pify(relike)(stream).then(console.log) // => value
pify(relike)(Observable.return([1, 2, 3])).then(console.log) // => [1, 2, 3]
pify(relike)(Promise.resolve(123)).then(console.log) // => 123