I want to know if there is a way to write a function that can execute any type of function whether it's async or not. I want to make sure to get the return value or if some error occurred while execution.
            Asked
            
        
        
            Active
            
        
            Viewed 37 times
        
    0
            
            
        - 
                    I think you'll have to give us a more concreate description of what you're trying to do. You call a function the same whether it's asynchronous or not. Extracting the return value from an asynchronous function depends entirely upon how the function is written. It needs to either accept a callback that will be called upon completion or error or it needs to return a promise that will resolve with the final value upon success and reject upon error. – jfriend00 Sep 22 '21 at 08:46
- 
                    https://stackoverflow.com/a/27760489/457268 – k0pernikus Sep 22 '21 at 09:18
- 
                    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 29 '21 at 17:17
- 
                    I have an object that contains properties that are functions. like a router for instance that executes handlers. I don't know what type of a function I'm getting but I don't want my app to crash if something goes wrong while executing. bear in mind that I'm not using express just vanilla JS. if there's a setTimeout in that function that throws an error I can't catch it even while wrapping the caller function in try/catch and my app crashes. – cacuto hana Sep 30 '21 at 09:15
1 Answers
0
            
            
        You can pass the function to an async function and have it wait for completion.
async function exec(myFunc, args = []) {
    return await myFunc(...args);
}
function myExampleAddFunction(a, b) {
    return new Promise((resolve, reject) => {
        console.log('Hello');
        resolve(a + b);
  });
}
const result = await exec(myExampleAddFunction, [1, 2]);
args is an optional parameter where you can pass your function's arguments as an array.
This will work irrespective of whether the function returns a value or a promise.
 
    
    
        Mythos
        
- 1,378
- 1
- 8
- 21
