Skip to content

Commit

Permalink
Merge a804413 into 95d9ba8
Browse files Browse the repository at this point in the history
  • Loading branch information
Richienb committed Oct 10, 2020
2 parents 95d9ba8 + a804413 commit 8286140
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
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)

})
})

0 comments on commit 8286140

Please sign in to comment.