Skip to content

Instantly share code, notes, and snippets.

@TechNinjaWeb
Created April 26, 2016 07:00
Show Gist options
  • Save TechNinjaWeb/fb32dde509153d8ffd4874fe17367574 to your computer and use it in GitHub Desktop.
Save TechNinjaWeb/fb32dde509153d8ffd4874fe17367574 to your computer and use it in GitHub Desktop.
ES5 Promises & Error Handling
<div id="output">
</div>
/*
The purpose of this fiddle is to showcase the
power of ES5's Promise Async function using
try/catch/finally to do error handling, the
Array.reduce function to filter and recompile an
object (note the illegal use of Array as object),
and also the chaining method of the new Promise function.
You must wait 4 seconds for anything to happen!!!!!!!
You are likely to get errors due to the isTrue and
rejectIt variables being true/false
*/
// Primary Dom Element
var output = document.getElementById('output');
// Temporary Empty Var To Use As Ref
var results;
// Fake Conditions
// isTrue will run as a conditional argument
var isTrue = false;
// rejectIt will determine whether to resolve or
// reject the promise
var rejectIt = false;
// Empty Array Var
var arr;
// Define a promise object;
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
arr = [{
user: 'Ray',
age: 28
}, {
user: 'Jeff',
age: 32
}, {
user: 'Court',
age: 50
}];
// Try a condition
try {
// If It's True, resolve the data immediately
if (isTrue) null;
// If It's False, throw an error to the
// Catch statement. It's object is (e)
else throw new Error("There's Been An Error");
} catch (e) {
// Log the Error to Console for Client to See
console.error(e.message, e);
// Don't Reject The Error here
// reject({message: "Not True Man", arr});
} finally {
// Determine whether we should reject the array
// based on some other predetermined condition
// Here we use the fake rejectIt boolean
// If it's true, we halt the compiler and go no further
if (rejectIt) reject({message: "Not True Man", arr});
// If RejectIt is false, lets send the
// arr into the next .then function by
// resolving it
else resolve(arr);
}
// Wait Some amount of time
// Before we fire this function
}, 4000)
});
// Step 2 of the promise
promise.then(function(resultsOfLastStep) {
// We Create a User Variable to hold our
// Results of the reduce function.
// resultsOfLast Step is the object inside of
// the resolve function resolve('I Am resultOfLastStep');
var User = resultsOfLastStep.reduce(function(emptyArray, currentIteration, i, a) {
// Some Arbitrary condition
// Notice that we are illegally combining
// Object.Keys with an [array] notation
if (currentIteration.user === 'Jeff') emptyArray.objectInArrNumberOne = currentIteration;
// Some other Arbitrary condition
// Same illegal combination of objects and arrays
else if (currentIteration.user === 'Ray') emptyArray.objectInArrNumberTwo = currentIteration
// Some Last Arbitrary condition
// Push the entire currently iterated
// object into the empty array from the end of
// this function
if (currentIteration.age >= 30) emptyArray.push(currentIteration);
// Make sure we return the empty array so that
// Each consecutive iteration of the reduce function
// It adds new data to this array node
return emptyArray;
}, []);
// Set Empty Results Var to User;
return results = User;
});
// Step 3 of the promise
promise.then(function(nextStep){
// nextStep === User <-- returned value of last function
// Output to the Primary DOM Element
output.innerHTML = JSON.stringify(results);
// Simple Console log on the output data
console.log(["Data in the Output Div", output],
["User Object", results], ['Next Step Resolved Object', nextStep]);
// We'll try a fake try catch block
try {
// Let's determine if the isTrue boolean is set
// If it's true, just log to the console
if (isTrue) console.warn("Yay! Its True");
// If it's false, manually tell the compiler
// that we have an error
else throw new Error("You've Got Errors Mang");
} catch (e) {
// This Catch block will do something with
// The error we threw in the last step
// Just console.logs the error's message and the
// entire stack trace for better error handling
console.error({message: e.message, error: e});
} finally {
// Finally, we do something regardless
// of if the previous try/catch failed or passed
console.info("Just Going with the Flow", ['User Object Again', results]);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment