-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17.3.promises_in_depth.js
More file actions
43 lines (37 loc) · 1.15 KB
/
17.3.promises_in_depth.js
File metadata and controls
43 lines (37 loc) · 1.15 KB
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
// const cart=["shoes","pants","kurta"]
const cart=[]
// This is an asynchronous operation
const promise=createOrder(cart) // This will return me the order id
// console.log(promise);
// Consumer part...........
promise.then(function(orderId){
console.log(orderId);
// proceedToPayment(orderId);
}) // In case the promise fails you can use the catch function to handle it
.catch(function(err){
console.log(err.message);
})
// Producer Part..................
function createOrder(cart){ // It will return a promise over here
// Here we will create a promise and return it
const pr=new Promise(function(resolve,reject){
// createOrder
// ValidateCart
// orderId
if(!validateCart(cart)){ // If the cart is not validated you reject the promise
const err=new Error("Cart is not valid");
reject(err); // Reject the promise
}
// logic for createOrder
const orderId="12345"
if(orderId){
setTimeout(() => {
resolve(orderId);
}, 5000);
}
});
return pr;
}
function validateCart(cart){
return cart.length!=0;
}