diff --git a/beli.js b/beli.js index 060efcd..4699fc1 100644 --- a/beli.js +++ b/beli.js @@ -1,15 +1,20 @@ +"use strict" function beli(uang, obj, cb){ console.log(`Saya pergi membeli ${obj.item}`) - setTimeout(function(){ - let kembalian = uang - obj.harga - if (kembalian > 0) { - console.log(`Saya sudah membeli ${obj.item} uang kembaliannya ${kembalian}`); - cb(kembalian) - }else{ - console.log(`uang gk cukup nih buat beli ${obj.item} kembaliannya cuma ${kembalian}`); - cb(0) - } - }, obj.waktu); + return new Promise(function(resolve, reject) { + setTimeout(function(){ + let kembalian = uang - obj.harga + if (kembalian > 0) { + console.log(`Saya sudah membeli ${obj.item} uang kembaliannya ${kembalian}`); + resolve(kembalian) + + }else{ + console.log(`uang gk cukup nih buat beli ${obj.item} kembaliannya cuma ${kembalian}`); + reject(0) + } + }, obj.waktu); + }); } + module.exports = beli; diff --git a/index.js b/index.js index e69de29..5a25812 100644 --- a/index.js +++ b/index.js @@ -0,0 +1,50 @@ +"use strict" +const beli=require('./beli.js') +var uang=10000 +var obj=[{ + item:'kopi', + harga: 2000, + waktu : 2000 + }, + { + item:'permen', + harga: 500, + waktu: 2000 + }, + { + item:'teh', + harga: 5000, + waktu: 2000 + }, + { + item:'ciki', + harga: 3500, + waktu: 2000 + }, + { + item:'kue', + harga: 1000, + waktu: 2000 + } + ] + +beli(uang,obj[0]).then(sisa=>{ + beli(sisa,obj[1]).then(sisa=>{ + beli(sisa,obj[2]).then(sisa=>{ + beli(sisa,obj[3]).then(sisa=>{ + beli(sisa,obj[4]).then(sisa=>{ + }).catch(err=>{ + console.log(err); + }) + }).catch(err=>{ + console.log(err); + }) + }).catch(err=>{ + console.log(err); + }) + }).catch(err=>{ + console.log(err); + }) +}).catch(err=>{ + console.log(err); +})