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

JavaScript

*** using callback ***

JavaScript

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.

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement