From 6e6d26b8cbedfaea37ef4fada9ce7318c5e02745 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 20 Feb 2018 16:04:45 +0700 Subject: [PATCH] promise belanja --- beli.js | 29 ++++++++++++++++------------- index.js | 14 ++++++++++++++ 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/beli.js b/beli.js index 060efcd..38df66c 100644 --- a/beli.js +++ b/beli.js @@ -1,15 +1,18 @@ -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); +class Belanja { + static beli(uang, obj) { + return new Promise((resolve, reject)=>{ + console.log(`Saya pergi membeli ${obj.item}`) + setTimeout(()=>{ + let kembalian = uang - obj.harga + if(kembalian > obj.harga) { + console.log(`Saya sudah membeli ${obj.item} uang kembaliannya ${kembalian}`) + resolve(kembalian) + } else { + reject(`uang gak cukup nih buat beli ${obj.item} kembaliannya cuma ${kembalian}`) + } + }, obj.waktu) + }) + } } -module.exports = beli; +module.exports = Belanja; \ No newline at end of file diff --git a/index.js b/index.js index e69de29..35a1f65 100644 --- a/index.js +++ b/index.js @@ -0,0 +1,14 @@ +const Belanja = require('./beli.js') + +let indomie = {item: 'indomie', harga: 1500, time: 500} +let sarden = {item: 'sarden', harga: 7000, waktu: 500} +let gula = {item : 'gula', harga: 4000, waktu: 500} +let garam = {item : 'garam', harga: 3000, waktu: 500} +let royco = {item : 'royco', harga: 2000, waktu: 500} + +Belanja.beli(10000, indomie) + .then(kembalian => {Belanja.beli(kembalian, sarden) + .then(kembalian => {Belanja.beli(kembalian, gula) + .then(kembalian => {Belanja.beli(kembalian, garam) + .then(kembalian => {Belanja.beli(kembalian, royco)})})}) + .catch(err => {console.log(err)})}) \ No newline at end of file