Skip to content

Commit

Permalink
feat: thenable/ensure
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Apr 4, 2019
1 parent 2711d70 commit 6762c0d
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,18 @@ isThenable({ then: () => {} }); // true
isThenable({}); // false
```

##### `thenable/ensure`

If given argument is a thenable object, it is returned back. Otherwise `TypeError` is thrown.

```javascript
const ensureThenable = require("type/thenable/ensure");

const promise = Promise.resolve();
ensureThenable(promise); // promise
ensureThenable({}); // Thrown TypeError: [object Object] is not a thenable object
```

---

### Error
Expand Down
20 changes: 20 additions & 0 deletions test/thenable/ensure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"use strict";

var assert = require("chai").assert
, ensureThenable = require("../../thenable/ensure");

describe("thenable/ensure", function () {
it("Should return input value", function () {
var value = { then: function () { return true; } };
assert.equal(ensureThenable(value), value);
});
it("Should crash on no value", function () {
try {
ensureThenable({});
throw new Error("Unexpected");
} catch (error) {
assert.equal(error.name, "TypeError");
assert.equal(error.message, "[object Object] is not a thenable object");
}
});
});
9 changes: 9 additions & 0 deletions thenable/ensure.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"use strict";

var resolveException = require("../lib/resolve-exception")
, is = require("./is");

module.exports = function (value/*, options*/) {
if (is(value)) return value;
return resolveException(value, "%v is not a thenable object", arguments[1]);
};

0 comments on commit 6762c0d

Please sign in to comment.