Now is the time to look at callbacks in detail. Follow along with Srishti in the next video.
In the last video, you looked at an example where you are getting the name of a user from the server and after getting the name, you want to greet the user. Now, you know that getting data from the server will actually take some time. In order to mock the functionality of getting the name from the server, you use a setTimeout() method and assume that the server will respond with the name from the database after 2 seconds. Following is the code, which you looked and represents this scenario:
Code Snippet:
let name; const getName = () => { // get data from database setTimeout(() => { name = "Srishti"; }, 2000); } const greet = () => { console.log(`Hello ${name}`); } getName(); greet();
Output:
Hello undefined
You also looked at the problem where the greet() function is called before the getName() function is able to assign a value to the name variable, thus printing the value of name variable as undefined.
You looked at one of the solutions to this problem as making the greet() function an anonymous function but this is not what really happens in practice.
Look at the next video to learn from Srishti how this problem can be solved using a callback.
In the last video, you learned how a callback can be used to solve the above problem with asynchronous programming. You also learned that callback is not a keyword but just the name given to a parameter to hold a function. You can name it whatever you like, but just keep it meaningful.
Following is the code utilizing callbacks which you looked at in the last video:
Code Snippet:
let name; let getName = (cb) => { // get name from DB setTimeout(() => { name = "Srishti"; cb(); }, 2000); } let greet = () => { console.log(`Hello ${name}`); } getName(greet);
Output:
Hello Srishti
If you are still not sure how the solution worked using callbacks, watch the next video where Srishti explains again in detail the flow in which the solution code works.
Hope that the solution using a callback to the above problem is clear to you!
Till now, you have seen just a normal callback without accepting any argument. In the next video, you’ll look at how an argument can be passed to a callback and how it can handle it.
Following is the code snippet, which you looked at in the last video:
Code Snippet:
let getName = (cb) => { let name; // get name from DB setTimeout(() => { name = "Srishti"; cb(name); }, 2000); } let greet = (nameVal) => { console.log(`Hello ${nameVal}`); } getName(greet);
Output:
Hello Srishti