skip to Main Content
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


  1. 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 the if outside setTimeout().

    function getdata(id, callback) {
      console.log(id)
      if (callback) {
        setTimeout(callback, 2000)
      }
    }
    
    getdata(1, () => getdata(2));
    Login or Signup to reply.
  2. getdata(2) is executed immediately when getdata(1, getdata(2)) is called. This is because arguments in JavaScript are evaluated before the function is called.

    To ensure getdata(2) is called after getdata(1), you need to pass getdata(2) as a callback function:

    function getdata(id,callback){
     console.log(id)
      
      setTimeout(()=>{
       
        if(callback){
         callback();
        }
      },2000)
    
    }
    getdata(1, () => {
      getdata(2);
    });

    By passing () => { getdata(2); } as the second argument to getdata(1), you ensure that getdata(2) is called only after getdata(1) completes and the timeout expires.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search