0

I have across a block of code that I couldn't really tackle. It is written as following:

function getValue (callback) {
  setTimeout(() => {
    callback("B")
  }, 10)
} 

How can we call this function to return the string, "B" as it has a callback inside a timeout of 10ms. Any help? I have tried calling it normally but it returns undefined. Can anyone explain how this block of code works?

--Here is the problem that was supposed to be solved. There are three functions that return A,B,C respectively as strings and the goal here is to get the output to be printed the same as above (A,B,C).

function getA () {
  return "A"
} 

const getB = async () => { const b = await "B"; return b }

function getC (callback) {
  setTimeout(() => {
  callback("C")
  })
} 
Saif
  • 249
  • 5
  • 15
  • 1
    You pass in a function. It calls the function. It is the basic concept of callbacks where you call something and it calls a function to say it is done. – epascarello Dec 20 '21 at 13:35
  • I have tried it and it didn't work. Keep in mind that there is a setTimeout wrapping the callback. – Saif Dec 20 '21 at 13:36
  • [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Andreas Dec 20 '21 at 13:36
  • `function foo (x) { console.log(x); /* do what you want with the value here */} getValue(foo);` – epascarello Dec 20 '21 at 13:38
  • `I have tried it and it didn't work` We have no clue what you tried that did not work. – epascarello Dec 20 '21 at 13:39
  • Basic concept. You order a pizza online. You submit the form. 30 minutes later your doorbell rings and the pizza is there. That "callback" function is your doorbell. It tells you when it is done. So you stick what ever needs to use that value inside of the callback. – epascarello Dec 20 '21 at 13:41
  • @epascarello I have updated the post. Would you pls have a look? – Saif Dec 20 '21 at 13:50
  • So you call it like I did in my comment above. You pass in a function. – epascarello Dec 20 '21 at 13:54
  • @epascarello Well. Conole.log works but when I try to return the value and store it in a variable, it returns undefined. Also, I want to get the results of all functions combined in an array, ["A", "B", "C"] – Saif Dec 20 '21 at 13:58
  • You can not return from a callback. You have to work with the value inside of the callback. That is how callbacks work. `async function output (valueC) { const valueA = getA(); const valueB = await getB(); console.log(valueA, valueB, valueC); } getC(output);` – epascarello Dec 20 '21 at 13:59

0 Answers0