Last active
June 14, 2019 11:46
-
-
Save spunkypanda/0ab9231a27195d12824f147529d9b720 to your computer and use it in GitHub Desktop.
Evolution of Promise syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const originalFunctionWithPromise = (num) => new Promise((resolve, reject) => { | |
try { | |
if (typeof num !== 'number') { | |
return reject(new Error('Invalid input')); | |
} | |
return resolve(5 * num); | |
} catch (err) { | |
return reject(err); | |
} | |
}); | |
const originalFunction = async (num) => { | |
try { | |
if (typeof num !== 'number') { | |
throw new Error('Invalid input'); | |
} | |
return (5 * num); | |
} catch (someError) { | |
throw someError; | |
} | |
}; | |
const modifiedFunction = async (num1, num2) => { | |
if (typeof num1 !== 'number' || typeof num2 !== 'number') { | |
throw new Error('INVALID_INPUT'); | |
} | |
return (10 * num1 * num2); | |
}; | |
const errorHandler = fn => async (...args) => { | |
try { | |
const res = await fn(...args); | |
return res; | |
} catch (someError) { | |
throw someError; | |
} | |
}; | |
const differentErrorHandler = fn => async (...args) => { | |
try { | |
const res = await fn(...args); | |
return res; | |
} catch (someError) { | |
if (someError.message === 'INVALID_INPUT') { | |
const InvalidInputError = new Error('Maybe try using a number next time'); | |
throw InvalidInputError; | |
} | |
throw someError; | |
} | |
}; | |
const modifiedFunctionWithErrorHandling = errorHandler(modifiedFunction); | |
const modifiedFunctionWithDifferentErrorHandling = differentErrorHandler(modifiedFunction); | |
async function init() { | |
try { | |
const result1 = await modifiedFunctionWithErrorHandling(3, 2); | |
console.log('Result 1 :', result1); | |
const result2 = await modifiedFunctionWithErrorHandling('chinmay', 2); | |
console.log('Result 2 :', result2); | |
} catch (err) { | |
console.error('Simple Error:', err.message); | |
} | |
try { | |
const result3 = await modifiedFunctionWithDifferentErrorHandling('chinmay', 2); | |
console.log('Result 3: ', result3); | |
} catch (err) { | |
console.error('Different Error: ', err.message); | |
} | |
} | |
init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment