Skip to content
Advertisement

How should I use the callback to get the desired outcome?

Hello there I am getting the desired result when am using promise but how should I implement it with callback when am returning something from the function.

result with promise


const first = () => {
    return ("I am first");
}

const second = () => {
  return new Promise((resolve,reject) => {
      setTimeout(()=>{
        resolve("I am second");
      },1000);
  })
}

const third = () => {
    return("I am third");
}

//using promise

const solve = async () => {
  var f = first();
  console.log(f);
  
  var ans = await second();
  console.log(ans);
  
  var t = third();
  console.log(t);
}

solve();

*** using callback ***

const first = () => {
    return "I am first";
}

var temp;
const second = (cb) => {
   setTimeout(function() {
    return "I am second";
    temp = cb();
   }, 1000);
}

const third = () => {
   return "I am third";
}


const solve = () => {
    var f  = first();
    console.log(f);
    
    var s = second(third);
    setTimeout(()=>{
      console.log(s);
      console.log(temp);
    },1100)
}

solve();

OUTPUT should be

I am first
I am second
I am third

Advertisement

Answer

You don’t need that global temp variable, and your setTimeout callback in second doesn’t really work. It should be cb("I am second");, just like where you’d usually call resolve("I am second"); in a new Promise. Then you can receive that value as the parameter of the callback function you’re passing to second(…), which should then log it and continue with the remaining steps of the script.

const first = () => {
    return "I am first";
}

const second = (cb) => {
    setTimeout(function() {
        cb("I am second");
    }, 1000);
}

const third = () => {
    return "I am third";
}


const solve = () => {
    var f  = first();
    console.log(f);
    
    second((s) => {
        console.log(s);

        const t = third();
        console.log(t);
    });
}

solve();

Notice this is not unlike your promise version if you were to use .then() instead of async/await syntax:

const solve = () => {
    var f = first();
    console.log(f);
  
    second().then((s) => {
        console.log(s);
  
        var t = third();
        console.log(t);
    });
}
Advertisement