Callback And Promises

Callback And Promises

A Bref Explanation About Callback And Promises

When your program running, think you have to continue execution ahead but there is some time-consuming function that has to be executed, but you can't stop there and wait to execute that one, so you can use the callback function in JS

Callback Function

A callback is a function that is passed into another function as an argument to be executed later.

ex:

console.log('Started');

function getdata(id) {
    setTimeout(() => {
        console.log('Timeout Set');
        return { items: [1, 2, 3, 4, 5] };
    }, 3000);
};

const items = getdata(1);
console.log(items);

console.log('End');

Code Output

Started
undefined
End
Timeout Set

You can see there is no output and it is shown as undefined, It can fix by using a callback function.

console.log('Started');

function getdata(id, callback) {
    setTimeout(() => {
        console.log('Timeout Set');
        callback({ items: [1, 2, 3, 4, 5] });
    }, 3000);
};

const items = getdata(1, items => {
    console.log(items);
});

console.log('End');

This is the output when we use the callback function.

Started
End
Timeout Set
{ items: [ 1, 2, 3, 4, 5 ] }

How it Happens....?

When you call the callback function in the second code you can see it not return anything and calling the callback function. when it executing it executes normally and found any time-consuming function execution ignore the current function and it continues, (but the ignore function is executing in the background), after the previous function is executed it automatically assign output values and it calls the related codes it related.