DEV Community

Fatima Alam
Fatima Alam

Posted on

JavaScript: CallBack Hell

function getArticlesData(id, callback) {
    // Simulate async operation
    setTimeout(() => {
        callback([{ username: 'user1' }, { username: 'user2' }]); // Dummy data
    }, 1000);
}

function getUserData(username, callback) {
    // Simulate async operation
    setTimeout(() => {
        callback(username + '_name'); // Dummy transformation
    }, 1000);
}

function getAddress(name, callback) {
    // Simulate async operation
    setTimeout(() => {
        callback(name + '_address'); // Dummy transformation
    }, 1000);
}

// Calling the functions in a callback hell manner
getArticlesData(20, (articles) => {
    console.log("article lists", articles);
    // Assuming you want to process the first article in the list
    getUserData(articles[0].username, (name) => {
        console.log(name);
        getAddress(name, (item) => {
            console.log(item);
            // This goes on and on...
        });
    });
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)