Logo Putra Jaya
Putra Jaya Manusia Biasa

Callback Function di JavaScript

// CARA PAKAI FUNGSI CALLBACK
const API_URL = "https://jsonplaceholder.typicode.com/todos/1";

function getData(url, callback) {
	fetch(url)
		.then((response) => response.json())
		.then((data) => {
			callback(null, data);
		})
		.catch((error) => {
			callback(error, null);
		});
}

getData(API_URL, (error, data) => {
	if (error) {
		console.log("Terjadi Error: ", error);
	} else {
		console.log("Data Diterima: ", data);
	}
});

// OUTPUT:
// Data Diterima:
// {
//    userId: 1,
//    id: 1,
//    title: 'delectus aut autem',
//    completed: false
// }