Last active
December 23, 2023 15:50
-
-
Save dooderstem/d3371da42aa3bc356f87b58b8eb27753 to your computer and use it in GitHub Desktop.
Async JavaScript - Creating promises and handling promise chains.
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
/** | |
* @author doodercodes | |
* @description Async JavaScript - Creating promises and handling promise chains. | |
* @description JAVASCRIPT WAITS FOR NOTHING! | |
* @date 08/03/2023 | |
**/ | |
const cart = randCart(); | |
createOrder(cart) | |
.then((orderID) => orderID) | |
// .catch((err) => console.error(`\r\nERROR: ${err.message}`)) | |
.then((orderID) => proceedToPayment(orderID)) | |
.catch((err) => console.error(`\r\nERROR: ${err.message}`)) | |
.then((paymentInfo) => { | |
if (!paymentInfo) return; | |
console.log(paymentInfo); | |
}); | |
function createOrder(cart) { | |
return new Promise((resolve, reject) => { | |
if (!validateCart(cart)) { | |
const error = new Error("Cart is not valid"); | |
reject(error); | |
return null; | |
} | |
let orderID = id(); | |
console.log("Creating order..."); | |
console.info(cart); | |
console.info(orderID); | |
function id() { | |
let orderID = null; | |
function randID() { | |
for (let i = 0; i <= Math.floor(Math.random() * 4); i++) { | |
switch (i) { | |
case 0: | |
orderID = ""; | |
case 1: | |
orderID = 1; | |
break; | |
case 2: | |
orderID = "19982002-MS"; | |
break; | |
case 3: | |
orderID = "57548345-HF"; | |
break; | |
} | |
} | |
if (orderID === "") return null; | |
return orderID; | |
} | |
return randID(); | |
} | |
setTimeout(() => { | |
if (!orderID) orderID = null; | |
resolve(orderID); | |
}, 2000); | |
}); | |
} | |
function proceedToPayment(orderID) { | |
return new Promise((resolve, reject) => { | |
if (!orderID || typeof orderID !== "string" || orderID === "") { | |
const error = new Error( | |
`orderID is null or contains the wrong datatype\r\norderID: ${orderID}` | |
); | |
reject(error); | |
return; | |
} | |
console.log(`OrderID Created: ${orderID}`); | |
resolve("Payment successful"); | |
}); | |
} | |
function randCart() { | |
let cart = null; | |
for (let i = 0; i <= Math.floor(Math.random() * 3); i++) { | |
switch (i) { | |
case 0: | |
cart = ["shoes", "pants", "kurta"]; | |
break; | |
case 1: | |
cart = []; | |
break; | |
case 2: | |
cart = 0; | |
break; | |
} | |
} | |
return cart; | |
} | |
function validateCart(cart) { | |
return cart.length == 0 || !Array.isArray(cart) ? false : true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment