diff --git a/beli.js b/beli.js index 060efcd..602ca56 100644 --- a/beli.js +++ b/beli.js @@ -1,15 +1,22 @@ -function beli(uang, obj, cb){ +function beli(uang, obj){ 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((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}. Sisa uang ${uang}`); + reject(0) + } + }, obj.waktu); + + }) + } + + + module.exports = beli; diff --git a/index.js b/index.js index e69de29..6f43676 100644 --- a/index.js +++ b/index.js @@ -0,0 +1,40 @@ +// const fs = require('fs'); +const beli = require('./beli.js'); + +var obj1 = {}; +obj1.item = 'bubur'; +obj1.harga = 1000; +obj1.waktu = 2000; + +var obj2 = {}; +obj2.item = 'ayam'; +obj2.harga = 2000; +obj2.waktu = 2000; + +var obj3 = {}; +obj3.item = 'sayur'; +obj3.harga = 4000; +obj3.waktu = 2000; + +var obj4 = {}; +obj4.item = 'nasi'; +obj4.harga = 5000; +obj4.waktu = 2000; + +var obj5 = {}; +obj5.item = 'sate'; +obj5.harga = 7000; +obj5.waktu = 2000; + +beli(2000,obj1).then(success => {console.log(success); + beli(success,obj2).then(success => {console.log(success); + beli(success,obj3).then(success => {console.log(success); + beli(success,obj4).then(success => {console.log(success); + beli(success,obj5).then(success => {console.log(success); + + }).catch(error => {console.log(error);}); + }).catch(error => {console.log(error);}); + }).catch(error => {console.log(error);}); + }).catch(error => {console.log(error);}); +}).catch(error => {console.log(error);}); + diff --git a/testPromis.js b/testPromis.js new file mode 100644 index 0000000..cb527b8 --- /dev/null +++ b/testPromis.js @@ -0,0 +1,34 @@ +// function Sandwich(stock) { +// return new Promise ((resolve,reject) => { +// if (stock >= 1) { +// resolve ('Ini mas cheese burgernya !') +// } else { +// reject ('Maaf mas burgernya habis !') +// } +// }) + +// } + +// Sandwich(0).then(success => { +// console.log(success) +// }).catch(error => { +// console.log(error); +// }) + + +// class Burger { +// constructor() { +// } +// static getOrder(stock) { +// return new Promise ((resolve,reject) => { +// if (stock >= 1) {resolve ('Ini mas cheese burgernya !')} +// else {reject ('Maaf mas burgernya habis !')} +// }) +// } +// } + +// Burger.getOrder(3).then(success => { +// console.log(success) +// }).catch(error => { +// console.log(error); +// }) \ No newline at end of file