Help to understand asynchronous code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Help to understand asynchronous code

Hey, guys! I still have trouble with understanding async in JS. I've already asked a similar question, but I still don't understand. I got the base concept (I hope) and wrote some pieces of code to practice: https://code.sololearn.com/WMUVW53cjVt8/#js this one works fine I execute two functions. I get two messages from the first one, then the second function finishes and I got the message from the callback I put in the first function. That ok and you can't imagine, how proud I was when I guessed about .bind(). So, you can see, that I understood very basic ideas of async. But the second code doesn't work ok. https://code.sololearn.com/Wh1dmPQ0MifP/#js const getNumber = (cb) => { setTimeout(() => cb, 1000); } const findSquare = (n) => n * n; console.log(getNumber(findSquare(5))); //undefined console.log(getNumber(4)); //undefined Again, I have functions, one of them gets the callback that should be executed in some time. So, getNumber will finish before its callback, right? I can't understand how to get the value from such functions. Because they can't just get the value that doesn't exist yet and it always is undefined. Please, help me understand how exactly it works and how to repair my code.

20th Jul 2020, 4:37 PM
Nika Nika
1 Answer
+ 1
First of all, the findSquare method returns a number. So when you pass findSquare(5) to getNumber, you are passing 25 to getNumber, which actually expects a function. If you pass arguments after the second argument to the setTimeout function, they are passed to the destination function. So setTimeout(getSqaure, 1000, 5) will pass the 3rd argument to the getSquare function. So you can modify your code to achieve that. Also, getSquare only returns the square. You also need to log it to the console. So I suggest you change the definition to (n) => {console.log(n)}
20th Jul 2020, 5:01 PM
XXX
XXX - avatar