Wait for a function if it returns a promise (but you're not sure it does)

Posted on: 2018-02-17

If you are working on an npm module, a library or a plugin system, there is times where might want to call a function without being sur it returns a promise or not. Here is an example that may help you achieve what you want :

const returnsAPromise = () => Promise.resolve(); const returnsARejectedPromise = () => Promise.reject(`Error !`); const returnsOne = () => 1; const asyncFunction = async (unknwnFunction) => { await returnsAPromise(); // obvioulsy that passes try { await returnsARejectedPromise() } catch (e) { // obviously that fails... console.log(`Of course that failed :`, e); } // now... const one = await returnsOne(); // thats fine and one === 1 console.log(`I waited a regular function, one = ${one}`); // So it means that if we dont know if a function returns a promise // or just a value // we can just const result = await unknwnFunction(); // it is usefull when you are, for example, // programmig an npm module and the function you call is // provided by the user console.log(`unknownFunction returned (wrapped in a promise or not): ${result}`); }; const regularFunction = (unknwnFunction) => { // if we are not in a async function, we can also do : return Promise.resolve(unknwnFunction()) .then(result => { console.log(`whatever unknownFunction returned : `, result); }) .then(() => { // and yes, it would work even if the function fails : return Promise.resolve(returnsARejectedPromise()); }) .catch(err => { // this code is executed console.error(`It failed :`, err); }); }; asyncFunction(() => `Hi there !`) .then(() => regularFunction(() => `Hello ladies !`))