diff --git a/beli.js b/beli.js index 060efcd..036c691 100644 --- a/beli.js +++ b/beli.js @@ -1,15 +1,17 @@ -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); +function beli(uang, obj){ + return new Promise (function(resolve, reject){ + 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}`); + 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..401df0d 100644 --- a/index.js +++ b/index.js @@ -0,0 +1,62 @@ +const beli = require('./beli.js') + +let obj5 = { + item: 'kaos', + harga: 100000, + waktu: 1000 +} +let obj6= { + item: 'sepatu', + harga: 350000, + waktu: 1000 +} +let obj7= { + item: 'sendal', + harga: 80000, + waktu: 1000 +} +let obj8= { + item: 'topi', + harga: 60000, + waktu: 1000 +} +let obj9= { + item: 'jaket', + harga: 200000, + waktu: 1000 +} + +let duit = 1500000 + + +beli(duit, obj5) + .then(function(kembalian){ + beli(kembalian, obj6) + .then(function(kembalian){ + beli(kembalian, obj7) + .then(function(kembalian){ + beli(kembalian, obj8) + .then(function(kembalian){ + beli(kembalian, obj9) + .then(function(kembalian){ + + }) + .catch(function(err){ + console.log(err) + }) + }) + .catch(function(err){ + console.log(err) + }) + }) + .catch(function(err){ + console.log(err) + }) + }) + .catch(function(err){ + console.log(err) + }) + }) + .catch(function(err){ + console.log(err) + }) \ No newline at end of file