-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (64 loc) · 1.75 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*!
* promise2stream <https://github.com/hybridables/promise2stream>
*
* Copyright (c) 2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
* Released under the MIT license.
*/
'use strict'
var then = require('then-callback')
var through2 = require('through2')
var isPromise = require('is-promise')
/**
* > Transform a Promise `val` to transform stream.
*
* **Example**
*
* ```js
* var promise2stream = require('promise2stream')
* var promise = Promise.resolve(123)
*
* var stream = promise2stream(promise)
* stream
* .on('data', function (val) {
* console.log(val) // => 123
* })
* .once('error', console.error)
* .once('end', function () {
* console.log('end')
* })
*
* // or access the promise
* stream.promise.then(function (val) {
* console.log(val) // => 123
* }, console.error)
*
* // rejected promise fires `error` event
* var rejectedPromise = Promise.reject(new Error('foo err'))
* var stream = promise2stream(rejectedPromise)
*
* stream.once('error', function (err) {
* console.log(err) // => [Error: foo err]
* })
* ```
*
* @param {Promise} `val` Some promise.
* @param {Object} `opts` Options passed directly to [through2][].
* @return {Stream}
* @api public
*/
module.exports = function promise2stream (val, opts) {
if (!isPromise(val)) {
throw new TypeError('promise2stream: expect `val` be promise')
}
opts = typeof opts === 'object' ? opts : {}
opts.objectMode = typeof opts.objectMode === 'boolean' ? opts.objectMode : true
var stream = through2(opts)
stream.promise = val
stream.promise = then(stream.promise)
.then(function cb (err, res) {
if (err) return stream.emit('error', err)
stream.push(res)
stream.push(null)
})
return stream
}