-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.promise basic.js
69 lines (38 loc) · 1.81 KB
/
3.promise basic.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
/*
IOC: Inversion of control means you will lose the control over code when you use callbacks
Mainly call back has two problems
1. Callback hell: means your code grows horizontally instead of vertically
2. Inversion of control:
example:
api.createOrder(cart, function()
{
api.proceedToPayment(..)
})
so the problem is we need to rely on the createOrder function in order to excecute the callback. So the we are going to lose the control
over the code. If there are some bugs in the higher order func then the callback will never be excecuted/or may be excecuted in the wrong way.
*/
//difference between the callback hell and the promise
const cart=["laptops","gpu","bags"];
createOrderApi(cart,function (orderId){
proceedToPyament(orderId,function (paymentInfo){
paymentReceipt(paymentInfo,function (){
updateUserWallet();
});
});
});
//---------------------------------------------------------------------------------------------------------------
///promise
const promise = createOrderApi(cart); // promise returns an object with undefined value
//{key: fulfilled}; after the asynchronous operation when createOrderAPI done its work then `then()` works
promise.then(orderID=> {return proceedToPyament(orderID)});
//{key: fulfilled};
//---------------------------------------------------------------------------------------------------------------
//promise chaining
createOrderApi(cart)
.then(orderId => {return proceedToPyament(orderId)})
.then(paymentInfo => {return paymentReceipt(paymentInfo)})
.then(updateUserWallet());
//test a public api
const chicagoArtApi = "https://api.artic.edu/api/v1/artworks";
const user = fetch(chicagoArtApi); //fetch returns as a promise
user.then((x) =>{console.log(x); document.write("feteched")} ); // all the data in the console