function getdata(id, callback) {
console.log(id);
setTimeout(() => {
if (callback) {
callback();
}
}, 2000);
}
getdata(1, getdata(2));
I am not getting why getdata(2)
is executing first here. As per my understanding, it should print 1
first. I am confused about why the sequence is different. What if I write:
getdata(1, () => { getdata(2); });
How does this change make the sequence 1
, then 2
?
And also in above code this getdata(1,getdata(2)); looks valid and in below code its giving callback is not a function error?
function fun(num1,num2){
let result = num1+num2;
return result;
}
function last(callback){
if(callback){
const result = callback();
console.log(result)
}
}
last(fun(1,2));
2
Answers
The second argument to
getdata()
should be a callback function. You’re calling the function directly, not providing it as a callback.Change that argument to an anonymous function that does what you want.
You can also simplify
getdata()
by putting theif
outsidesetTimeout()
.getdata(2)
is executed immediately whengetdata(1, getdata(2))
is called. This is because arguments in JavaScript are evaluated before the function is called.To ensure
getdata(2)
is called aftergetdata(1)
, you need to passgetdata(2)
as a callback function:By passing
() => { getdata(2); }
as the second argument togetdata(1)
, you ensure thatgetdata(2)
is called only aftergetdata(1)
completes and the timeout expires.