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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay