Javascript promise defer library
Install
yarn add jdefer
Usage
Single promise with defer
In 2024: recommended using Promise.withResolvers()
.
import makeDefer from 'jdefer'
const makeDefer = require('jdefer')
const defer = makeDefer()
defer.reject(new Error('foo'))
defer.resolve('bar')
await defer.promise
Broadcast stream
import {makeBroadcastStream} from 'jdefer'
const {makeBroadcastStream} = require('jdefer')
const stream = makeBroadcastStream()
const removeListener = stream.listen(
(value) => {
console.log(value)
}, {
onDone() {
console.log('done')
},
onError(error) {
console.error(error)
},
})
removeListener()
stream.next('foo')
stream.throw(new Error('bar'))
stream.done()
for await (const value of stream) {
console.log(value)
}