try_catch_async.js (2222B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isFunction = require( '@stdlib/assert/is-function' ); 24 25 26 // MAIN // 27 28 /** 29 * If a function does not return an error, invokes a callback with the function result; otherwise, invokes a callback with a value `y`. 30 * 31 * @param {Function} x - function to invoke 32 * @param {*} y - value to return if `x` returns an error 33 * @param {Function} done - callback to invoke upon completion 34 * @throws {TypeError} first argument must be a function 35 * @throws {TypeError} last argument must be a function 36 * 37 * @example 38 * var randu = require( '@stdlib/random/base/randu' ); 39 * 40 * function x( clbk ) { 41 * setTimeout( onTimeout, 0 ); 42 * function onTimeout() { 43 * if ( randu() > 0.5 ) { 44 * return clbk( null, 1.0 ); 45 * } 46 * clbk( new Error( 'beep' ) ); 47 * } 48 * } 49 * 50 * function done( error, result ) { 51 * if ( error ) { 52 * console.log( error.message ); 53 * } 54 * console.log( result ); 55 * } 56 * 57 * trycatchAsync( x, -1.0, done ); 58 */ 59 function trycatchAsync( x, y, done ) { 60 if ( !isFunction( x ) ) { 61 throw new TypeError( 'invalid argument. First argument must be a function. Value: `'+x+'`.' ); 62 } 63 if ( !isFunction( done ) ) { 64 throw new TypeError( 'invalid argument. Last argument must be a function. Value: `'+done+'`.' ); 65 } 66 x( clbk ); 67 68 /** 69 * Callback invoked by `x`. 70 * 71 * @private 72 * @param {(Error|null)} error - error object 73 * @param {*} result - result 74 * @returns {void} 75 */ 76 function clbk( error, result ) { 77 if ( error ) { 78 return done( error, y ); 79 } 80 done( null, result ); 81 } 82 } 83 84 85 // EXPORTS // 86 87 module.exports = trycatchAsync;