-
Notifications
You must be signed in to change notification settings - Fork 0
/
5.promise chain.js
70 lines (65 loc) · 1.83 KB
/
5.promise chain.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
const cart = ["bag", "makeup kit", "bag"];
createOrder(cart)
.then((orderId) => {
console.log(orderId + " has been created");
return orderId;
})
.catch((err) => {
console.log(err); // Error from the createOrder promise
})
.then((orderId) => {
return proceedToPayment(orderId);
})
.then((paymentInfo) => {
console.log(paymentInfo); //show a message
return { orderId: paymentInfo.orderId, paymentStatus: paymentInfo.paymentStatus }; //pass some data to the down chain
})
.then(({ orderId, paymentStatus }) => {
return updateWallet(orderId, paymentStatus);
})
.then((updateWalletResolved) => {
console.log(updateWalletResolved);
})
.catch((err) => {
console.log(err);
});
function createOrder(cart) {
return new Promise((resolve, reject) => {
if (!validateCart(cart)) {
const err = new Error("Cart is not valid"); // Error throw
reject(err);
} else {
const orderId = Math.floor(Math.random() * 1000);
setTimeout(() => {
resolve(orderId); //orderID will go to the next chain
}, 2000);
}
});
}
function proceedToPayment(orderId) {
return new Promise((resolve, reject) => {
if (orderId) {
setTimeout(() => {
var paymentStatus = true;
resolve({orderId,paymentStatus}); //this json will go the next chain
return console.log("Payment successful"); //always return after resolve//
}, 1000);
} else {
reject("You did not choose any product");
}
});
}
function updateWallet(orderId, paymentStatus) {
return new Promise((resolve, reject) => {
if (paymentStatus === true) {
setTimeout(() => {
resolve("Wallet updated of order ID: " + orderId);
}, 1000);
} else {
reject("No change in the wallet " + orderId);
}
});
}
function validateCart(cart) {
return true;
}