Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ***

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading