Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add .promise() #26

Merged
merged 1 commit into from
Oct 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ niceTry(() => JSON.parse('true')) // true
niceTry(() => JSON.parse('truee')) // undefined
niceTry() // undefined
niceTry(true) // undefined

await niceTry.promise(async () => JSON.parse('true')) // true
await niceTry.promise(async () => JSON.parse('truee')) // undefined
```

## API
Expand Down
13 changes: 12 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,15 @@ module.exports = function(fn) {

try { return fn() } catch (e) {}

}
}

/**
* Tries to execute an asynchronous function and discards any error that occurs.
* @param {Function} fn - Asynchronous function that might or might not throw an error.
* @returns {?*} Promise which resolves with the return-value of the asynchronous function when no error occurred.
*/
module.exports.promise = async function (fn) {

try { return await fn() } catch (e) {}

}
11 changes: 11 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,15 @@ describe('index()', function() {

})

it('should return a value when called with an asynchronous function that returns a value', async function () {

assert.strictEqual(await index.promise(async () => JSON.parse('truee')), undefined)

})

it('should return undefined when called with an asynchronous function that throws an error', async function () {

assert.strictEqual(await index.promise(async () => JSON.parse('true')), true)

})
})