Skip to content

Commit

Permalink
v1.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
taburetkin committed May 17, 2019
1 parent 4e36fc6 commit c529ae6
Show file tree
Hide file tree
Showing 11 changed files with 870 additions and 872 deletions.
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"eol-last": 2,
"eqeqeq": 0,
"guard-for-in": 2,
"indent": [ 2, "tab", { "SwitchCase": 1 } ],
"indent": [ "error", 2, { "SwitchCase": 1 } ],
"key-spacing": [ 2,
{
"beforeColon": false,
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# v1.1.0, 2019-06-17
## enhancements:
- added type script definitions.
## additional
- code base now uses spaces instead of tabs.
217 changes: 114 additions & 103 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,90 +1,96 @@
# asyncresult-js
Small set of utils for working with promises.
# asyncresult-js

Small set of utils for working with promises.

![version](https://img.shields.io/github/package-json/v/taburetkin/asyncresult.svg)
[![Coverage Status](https://coveralls.io/repos/github/taburetkin/asyncresult/badge.svg?branch=master)](https://coveralls.io/github/taburetkin/asyncresult?branch=master)
![Build status](https://secure.travis-ci.org/taburetkin/asyncresult.svg?branch=master)
![TypeScript](https://img.shields.io/badge/ts--definitions-yes-green.svg)

## examples:

usual promise approach:

```js
fetchSomething().then(() => {
fetchSomethingElse().then(() => {
fetchLastThing().then((data) => {
showTheData(data);
}).catch(err => {
throw err;
});
}).catch(err => {
throw err;
});
}).catch(err => {
throw err;
});
fetchSomething()
.then(() => {
fetchSomethingElse()
.then(() => {
fetchLastThing()
.then(data => {
showTheData(data);
})
.catch(err => {
throw err;
});
})
.catch(err => {
throw err;
});
})
.catch(err => {
throw err;
});
```

usual async/await approach

```js
// suppose you are in some async context
async () => {
try {
await fetchSomething()
}
catch (err) {
throw err;
}

try {
await fetchSomethingElse()
}
catch (err) {
throw err;
}

try {
let data = await fetchLastThing();
showTheData(data);
}
catch (err) {
throw err;
}
}

try {
await fetchSomething();
} catch (err) {
throw err;
}

try {
await fetchSomethingElse();
} catch (err) {
throw err;
}

try {
let data = await fetchLastThing();
showTheData(data);
} catch (err) {
throw err;
}
};
```


and how it can be done with asyncresult-js

```js
import { wrapMethod } from 'asyncresult';
import { wrapMethod } from "asyncresult";
// wrapping methods with special util
const fetchSomethingAsync = wrapMethod(fetchSomething);
const fetchSomethingElseAsync = wrapMethod(fetchSomethingElse);
const fetchLastThingAsync = wrapMethod(fetchLastThing);

// assume we are in some async context
async () => {
let res = await fetchSomethingAsync();
if (res.isError()) {
throw res.err();
}

res = await fetchSomethingElseAsync();
if (res.isError()) {
throw res.err();
}

res = await fetchLastThingAsync();
if (res.isError()) {
throw res.err();
} else {
showTheData(res.val());
}
}


let res = await fetchSomethingAsync();
if (res.isError()) {
throw res.err();
}

res = await fetchSomethingElseAsync();
if (res.isError()) {
throw res.err();
}

res = await fetchLastThingAsync();
if (res.isError()) {
throw res.err();
} else {
showTheData(res.val());
}
};
```

--------------
---

# install

```
Expand All @@ -97,114 +103,114 @@ or
yarn add asyncresult-js
```


# content

## class AsyncResult - constructor(error, value)

> every wrapped and awaited method returns instance of AsyncResult
### instance methods

- **isError()**
returns `true` if there is error, empty string treated as error.
returns `true` if there is error, empty string treated as error.
- **isOk()**
returns `true` if there is no error
returns `true` if there is no error
- **isEmpty()**
returns `true` if there is no error and any value.
returns `true` if there is no error and any value.
- **hasValue()**
returns `true` if there is any value. empty string treated as value.
returns `true` if there is any value. empty string treated as value.

- **err()**
returns error.
returns error.
- **val()**
returns value.
returns value.
- **errOrVal()**
returns error or value in such order.
returns error or value in such order.

- **setValue(value)**
sets given value.
sets given value.
- **setError(err)**
sets given error.
sets given error.

### static methods

- **AsyncResult.success(value)**
shorthand for `new AsyncResult(null, value)`
shorthand for `new AsyncResult(null, value)`
- **AsyncResult.fail(erro)**
shorthand for `new AsyncResult(error)`
shorthand for `new AsyncResult(error)`

example

```js
import { AsyncResult } from 'asyncresult-js';
let r1 = new AsyncResult(null, 'foo'); // same as AsyncResult.success('foo')
import { AsyncResult } from "asyncresult-js";
let r1 = new AsyncResult(null, "foo"); // same as AsyncResult.success('foo')
console.log(r1.isError()); // false
console.log(r1.val()); // 'foo'


let r2 = new AsyncResult('foo'); // same as AsyncResult.fail('foo')
let r2 = new AsyncResult("foo"); // same as AsyncResult.fail('foo')
console.log(r1.isError()); // true
console.log(r1.err()); // 'foo'


```


## util toAsyncResult(arg, AsyncResultClass)
> converts given argument to a promise which will be resolved or rejected with AsyncResult instance.
If `arg` is instanceof `Error` then it will goes to the error value

> converts given argument to a promise which will be resolved or rejected with AsyncResult instance.
> If `arg` is instanceof `Error` then it will goes to the error value
**arg** - any, required
**AsyncResultClass** - optional, pass if you need your own extended AsyncResult

examples

```js
import { toAsyncResult } from 'asyncresult-js';
import { toAsyncResult } from "asyncresult-js";

// assume we are in some async context
async () => {

let mypromise = Promise.resolve('foo');
let value = await mypromise; // 'foo';
let mypromiseAsync = toAsyncResult(mypromise);
value = await mypromiseAsync; // AsyncResult { value: 'foo' }

}
let mypromise = Promise.resolve("foo");
let value = await mypromise; // 'foo';
let mypromiseAsync = toAsyncResult(mypromise);
value = await mypromiseAsync; // AsyncResult { value: 'foo' }
};
```

## util wrapMethod(method, options)
> returns new method which always return promise which will resolve with AsyncResult

> returns new method which always return promise which will resolve with AsyncResult
**method** - function, required.
**options** - object, optional.
**options** - object, optional.

### options

**context** - binds returned new function to this context.
**AsyncResult** - AsyncResult constructor, provide it if you need extended version of AsyncResult

examples

```js
import { wrapMethod } from 'asyncresult-js';
import { wrapMethod } from "asyncresult-js";

const myMethod = function() {
return 'foo'
}
return "foo";
};

const myAsyncMethod = wrapMethod(myMethod);

let result = myAsyncMethod(); // returns promise;

// assume we are in some async context
async () => {
result = await myAsyncMethod(); // returns AsyncResult with value 'foo';
}

result = await myAsyncMethod(); // returns AsyncResult with value 'foo';
};
```

## util addAsync(context, methodNames, options)
> adds async version of exist methods, founded by given names

> adds async version of exist methods, founded by given names
example:

```js
import { addAsync } from 'asyncresult-js'

Expand All @@ -219,7 +225,9 @@ addAsync(Something, ['foo', 'bar']); // adds to Something fooAsync, and barAsync
addAsync(Something, 'baz'); // adds to Something bazAsync method

```

in general its a sugar for this operation

```js
const Something = {
foo() { ... },
Expand All @@ -234,24 +242,27 @@ Something.fooAsync = wrapMethod(Something.foo, { context: Something })
**options** - object, optional.

### options

**context** - forced context, will be used internally in `wrapMethod` as context.
**AsyncResult** - AsyncResult class, in case you need extend version of AsyncResult.

## config

> keeps default AsyncResult class, you can replace it with your own.
Used by default if there is no AsyncResult option provided.
> Used by default if there is no AsyncResult option provided.
example

```js
import { config, wrapMethod } from 'asyncresult-js';
import { config, wrapMethod } from "asyncresult-js";
config.AsyncResult = MyOwnAsyncResult;

const test = () => true;
const testAsync = wrapMethod(test);

// assume we are in some async context
async () => {
const result = await testAsync();
console.log(result instanceof MyOwnAsyncResult); // true
}
const result = await testAsync();
console.log(result instanceof MyOwnAsyncResult); // true
};
```
Loading

0 comments on commit c529ae6

Please sign in to comment.