javascriptcallbackasynccallback

There is an exercise about async Callbacks an I am trying to solve it but I get error. How can I solve it?


Write a function called printAsyncName, which will take as parameters a callback and a string (which will be name). The callback function will simply print "Hello". The printAsyncName function will have to execute the callback function after an interval of 1 second. After an interval of 2 seconds, we must print the name that we take as a parameter.

Tips:

function printAsyncName(sayHello, name) {
  setTimeout(() => {
    console.log(name);
  }, 2000);
  let hello = setTimeout(() => {
    console.log("Hello");
  }, 1000);
  sayHello(hello);
}

printAsyncName("Jack");

And this is the error I got:

Process exited with code 1
Uncaught TypeError TypeError: sayHello is not a function
    at printAsyncName (/Users/arya/Downloads/es-73/exercise.js:8:3)
    at <anonymous> (/Users/arya/Downloads/es-73/exercise.js:11:1)
    at Module._compile (internal/modules/cjs/loader:1126:14)
    at Module._extensions..js (internal/modules/cjs/loader:1180:10)
    at Module.load (internal/modules/cjs/loader:1004:32)
    at Module._load (internal/modules/cjs/loader:839:12)
    at executeUserEntryPoint (internal/modules/run_main:81:12)
    at <anonymous> (internal/main/run_main_module:17:47)

Solution

  • function printAsyncName(name, callbackFunction) {
      setTimeout(() => {
        console.log(name);
      }, 2000);
        setTimeout(() => {
            callbackFunction;
      }, 1000);
    }
    
    callback = () => console.log('hello');
    printAsyncName('John', callback())