/** * @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; }