DEV Community

Guntur Poetra
Guntur Poetra

Posted on

Handle Async Promises Javascript

Apabila anda telah terbiasa menggunakan callback pada saat mengolah code yang bersifat asynchronous, itu adalah hal yang bagus.

Callback

Sekilas mengenai callback, sudah cukup apabila hanya menghandle flow kode yang tidak terlalu kompleks.

Tetapi apa yang terjadi apabila jumlah baris kode anda sangat banyak, tentu saja akan menyulitkan pada saat mengorganisir dan debugging khususnya.

function getAllUsers(url, callback) {
fetchAllUsers(url, function (error, response) {
processData(response.data, function (error1, data1) {
if (error1) {
return callback(error1);
}
processData1(data1, function (error2, data2) {
if (error2) {
return callback(error2);
}
processData2(data2, function (error3, data3) {
if (error3) {
return callback(error3);
}
processData3(data3, function (error4, data4) {
if (error4) {
return callback(error4);
}
callback(null, data4);
});
});
});
});
});
}
getAllUsers('https://localhost:3000/api/v1/users/', function (error, hasil) {
if (error) {
// Handle error
console.log(error);
} else {
// Proses data
console.log(hasil);
}
});

Kode diatas adalah contoh callback yang apabila semakin dalam subprosesnya (nested), maka kode akan semakin tidak rapi dan menyulitkan untuk mengorganisir kode. Kejadian seperti ini dikenal dengan istilah callback hell.

Promises

Promise (then)

Dengan adanya fitur promise, ini akan memudahkan kita dalam mengorganizir setiap potongan kode yang bersifat asynchronous.

getAllUsers(url).then((users) => {
console.log(users);
// ...
});
view raw promise-then.js hosted with ❤ by GitHub

Dari contoh diatas, kKita juga dapat membuat setiap potongan kode async menjadi pipeline yang tersusun rapi dan mudah untuk dibaca.

getAllUsers(url)
.then((users) => {
// do something with
return users
})
.then((results) => {
// ...
})
.then(result => {
// ...
})
.catch((error) => {
console.error(error);
})

Async-Await

Jika contoh diatas menggunakan promise, pada contoh ini kita akan menggunakan async dan await keyword. Keyword async-await memberikan cara lain dalam mengekspresikan penulisan code program kita. Perhatikan contoh potongan berikut

async function processUsers() {
const users = await getAllUsers();
const resultA = await processUser1(users);
const resultB = await processUser2(resultA);
const resultC = await processUser3(resultB);
const finalResult = await createToken(users, resultC);
return finalResult;
}
view raw async-await.js hosted with ❤ by GitHub

Bisa kita perhatikan, ekspresi kode dengan menggunakan async-await lebih ringkas dan flow code-nya terlihat friendly.

Conclusion

Setelah melihat dan mengerti cara menulis promise ataupun async-await, kita dapat menulis kode program kita menjadi lebih mudah dibaca dan lebih mudah manage kode program kita.

Penulisan menggunakan promise atau async-await cukup relative bergantung dengan context dan case setiap masalah yang akan diselesaikan.

Terkait

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay