Typography

活版印字


  • Home
  • Archive
  • Categories
  • Tags
  •  

© 2020 alincode

Theme Typography by Makito

Proudly published with Hexo

Promise Chaining

Posted at 2016-04-16 Promise Chain 

Promise 似乎可以更簡單做到 Chain Of Responsibility

範例
線上sandbox 你可以把 code 複製貼到這裡執行

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
var discountService = new Promise(function(resolve, reject) {
let orderPrice = 1000;
resolve(orderPrice);
});

var dptDiscount = function(orderPrice){
orderPrice *= 0.9;
return orderPrice;
};

var bigOrderDiscount = function(orderPrice){
orderPrice *= 0.95;
return orderPrice;
};

var vipDiscount = function(orderPrice){
orderPrice -= 100;
return orderPrice;
};

let result = discountService.then(function(orderPrice) {
return dptDiscount(orderPrice);
}).then(function(orderPrice) {
return bigOrderDiscount(orderPrice);
}).then(function(orderPrice) {
console.log(vipDiscount(orderPrice));
});

let result2 = discountService.then(function(orderPrice) {
return vipDiscount(orderPrice);
}).then(function(orderPrice) {
return dptDiscount(orderPrice);
}).then(function(orderPrice) {
console.log(bigOrderDiscount(orderPrice));
});

output

1
2
755
769.5

Share 

 Previous post: Sequelize 一對多更新 Next post: Chain Of Responsibility Design Pattern (javascript) 

© 2020 alincode

Theme Typography by Makito

Proudly published with Hexo