https://github.com/dirkluijk/promise-stream
A stream-like Promise for JavaScript
https://github.com/dirkluijk/promise-stream
Last synced: 6 months ago
JSON representation
A stream-like Promise for JavaScript
- Host: GitHub
- URL: https://github.com/dirkluijk/promise-stream
- Owner: dirkluijk
- Created: 2024-08-22T08:49:15.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-09-22T08:37:30.000Z (almost 2 years ago)
- Last Synced: 2024-09-22T08:38:43.292Z (almost 2 years ago)
- Language: TypeScript
- Size: 24.4 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# PromiseStream 🌊
> A stream-like promise that emits multiple values over time
[](https://www.npmjs.com/package/@dirkluijk/promise-stream)
[](https://www.npmjs.com/package/@dirkluijk/promise-stream)
[](https://github.com/dirkluijk/promise-stream/actions/workflows/main.yml)
## Overview
### What? 🤔
A simple building block that behaves like a regular `Promise`, but can emit multiple values over time.
* Compatible with async/await (awaits completion)
* Provides built-in async iterator
* Contains configurable buffer size
### Limitations & when to use? 🤷♂️
Like regular promises, a `PromiseStream` is not cancellable, is hot, shared, and will replay the last value.
Furthermore, no built-in operator support (like map or flatMap) is currently provided.
The limitations are intended. For extensive reactive apps I would recommend to use RxJS instead.
### Roadmap ideas 💡
* Provide built-in RxJS compatibility utils
* Support different backpressure mechanisms
## How to use 🌩
### Install
```
npm install @dirkluijk/promise-stream
```
### Creating a `PromiseStream`
This works the same as a regular `Promise`, but you have three callbacks: `next`, `complete` and `error`.
```typescript
import { PromiseStream } from '@dirkluijk/promise-stream';
const myStream = new PromiseStream((next, complete, error) => {
next('foo');
next('bar');
next('baz');
complete();
})
```
* `next` always expects a value
* `complete` never expects a value
* `error` accepts an optional error value
* once completed or failed, no values are accepted anymore
### Consuming a `PromiseStream`
You can use callbacks:
```typescript
myStream
.iterate(value => {
// executed when value is emitted
})
.then(() => {
// executed when completed
})
.catch((error) => {
// executed when failed
})
```
Since a `PromiseStream` invokes the `.then()` callback upon completion, it is compatible with async/await:
```typescript
try {
await myStream.iterate(value => {
// executed when value is emitted
});
} catch (error) {
// executed when failed
}
// executed when completed
```
Additionally, you can also use the async iterator:
```typescript
try {
for await (const value of myStream.asyncIterator()) {
// executed when value is emitted
};
} catch (error) {
// executed when failed
}
// executed when completed
```