Postingan lainnya
Apakab Promise bisa menggantikan Callback?
Kasus nya saya punya 3 ajax 1 ambil post 2 ambil comment 3 ambil tag jadi setelah 1 berhasil lanjut ke 2 dan ke 3 kalau saya menggunakan callback saya bisa atasi kasus ini, tapi kalau menggunakan Promise kira2 bisa gak ya? dan di promise nya tanpa menggunakan setTimeout
4 Jawaban:
Sangat bisa sekali. Justru kalo menurut saya untuk fungsi berkelanjutan lebih baik menggunakan promise. Misalkan semua fungsi menggunakan promise contohnya mungkin seperti ini
return ambilPost()
.then(ambilComment)
.then(ambilTag)
.catch(error);
Keuntungannya adalah fungsi kedua hanya akan berjalan setelah fungsi pertama selesai (resolved) dan seterusnya, tanpa harus menggunakan setTimeout. Dan dimanapun error muncul, entah di fungsi pertama, kedua atau ketiga, error akan muncul di fungsi catch. cmiiw
saya coba begini gak bisa
const req = require('request');
let movie = (id)=>{
let mov = new Promise((resolve, reject)=>{
let url = "http://www.omdbapi.com/?plot=full&i=";
req.get({url: url+id}, (err, res, body)=>{
return resolve(body);
});
});
mov.then((response)=>{
console.log(response);
let url = "http://www.omdbapi.com/?plot=full&i=tt446556";
req.get({url: url+id}, (err, res, body)=>{
console.log(body)
return body;
});
})
.then((response)=>{
console.log(response);
})
}
movie("tt4465564")
then yang ke 2 tidak bisa menunngu hasil dari then ke 1 jadinya console.log di then ke 2 kosong
problemnya ada disini
mov.then((response)=>{// mov adalah Promise
console.log(response);// disini Promise sudah resolved berupa 'response', karena itu then() kedua berjalan
let url = "http://www.omdbapi.com/?plot=full&i=tt446556";
req.get({url: url+id}, (err, res, body)=>{// req yang ini bukanlah promise
console.log(body)
return body;// return body tidak diteruskan ke then() kedua
});
})
.then((response)=>{// response empty karena return body diatas bukanlah promise
console.log(response);
})
Coba dengan kode seperti ini
mov.then((response)=>{
console.log(response);
return response;
})
.then((response)=>{
console.log(response);
})
Kalau memang mengharuskan untuk request url lain maka fungsi req harus dijadikan promise lagi
mov.then((response)=>{
console.log(response);
let url = "http://www.omdbapi.com/?plot=full&i=";
return new Promise((resolve, reject)=>{
req.get({url: url+id}, (err, res, body)=>{
console.log(body)
return resolve(body);
});
})
})
.then((response)=>{
console.log(response);
})
baiklah :D tapi menuturku bacanya jadi lebih rumit dari pada pakai callback