Skip to content

Instantly share code, notes, and snippets.

@Nalini1998
Last active April 19, 2023 21:18
Show Gist options
  • Save Nalini1998/5af71046564080403241c7637f181514 to your computer and use it in GitHub Desktop.
Save Nalini1998/5af71046564080403241c7637f181514 to your computer and use it in GitHub Desktop.
JAVASCRIPT PROMISES: One common pattern we’ll see with asynchronous programming is multiple operations which depend on each other to execute or that must be executed in a certain order. We might make one request to a database and use the data returned to us to make another request and so on! Let’s illustrate this with another cleaning example, w…
Chaining Multiple Promises
firstPromiseFunction()
.then((firstResolveVal) => {
return secondPromiseFunction(firstResolveVal);
})
.then((secondResolveVal) => {
console.log(secondResolveVal);
});
--------------------
const {checkInventory, processPayment, shipOrder} = require('./library.js');
const order = {
items: [['sunglasses', 1], ['bags', 2]],
giftcardBalance: 79.82
};
checkInventory(order)
.then((resolvedValueArray) => {
// Write the correct return statement here:
return processPayment(resolvedValueArray);
})
.then((resolvedValueArray) => {
// Write the correct return statement here:
return shipOrder(resolvedValueArray);
})
.then((successMessage) => {
console.log(successMessage);
})
.catch((errorMessage) => {
console.log(errorMessage);
});
https://www.codecademy.com/workspaces/64405531ef825878c091c4b7
@Nalini1998
Copy link
Author

Nalini1998 commented Apr 19, 2023

const checkInventory = (order) => {
return new Promise ((resolve, reject) => {
setTimeout(()=> {
const itemsArr = order.items;
let inStock = itemsArr.every(item => store[item[0]].inventory >= item[1]);

if (inStock){
let total = 0;
itemsArr.forEach(item => {
total += item[1] * store[item[0]].cost
});
console.log(All of the items are in stock. The total cost of the order is ${total}.);
resolve([order, total]);
} else {
reject(The order could not be completed because some items are sold out.);
}
}, generateRandomDelay());
});
};

const processPayment = (responseArray) => {
const order = responseArray[0];
const total = responseArray[1];
return new Promise ((resolve, reject) => {
setTimeout(()=> {
let hasEnoughMoney = order.giftcardBalance >= total;
// For simplicity we've omited a lot of functionality
// If we were making more realistic code, we would want to update the giftcardBalance and the inventory
if (hasEnoughMoney) {
console.log(Payment processed with giftcard. Generating shipping label.);
let trackingNum = generateTrackingNumber();
resolve([order, trackingNum]);
} else {
reject(Cannot process order: giftcard balance was insufficient.);
}

}, generateRandomDelay());
});
};

const shipOrder = (responseArray) => {
const order = responseArray[0];
const trackingNum = responseArray[1];
return new Promise ((resolve, reject) => {
setTimeout(()=> {
resolve(The order has been shipped. The tracking number is: ${trackingNum}.);
}, generateRandomDelay());
});
};

// This function generates a random number to serve as a "tracking number" on the shipping label. In real life this wouldn't be a random number
function generateTrackingNumber() {
return Math.floor(Math.random() * 1000000);
}

// This function generates a random number to serve as delay in a setTimeout() since real asynchrnous operations take variable amounts of time
function generateRandomDelay() {
return Math.floor(Math.random() * 2000);
}

module.exports = {checkInventory, processPayment, shipOrder};`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment