-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromiseChainAsynch.js
85 lines (78 loc) · 2.43 KB
/
promiseChainAsynch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const store = {
sunglasses: {
inventory: 817,
cost: 9.99,
},
pants: {
inventory: 236,
cost: 7.99,
},
bags: {
inventory: 17,
cost: 12.99,
},
};
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 };