-1

In JS, A function Main has 2 functions inside it. The second function should be executed after first function finishes the API call and has returned some value. How do I call the function secondFunction only after firstFunction returns any value and also be able to pass the value returned to the secondFunction.

function Main(ID) {
  firstFunction(ID)
  secondFunction()
}

function firstFunction(ID) {
  //async call 
}

function secondFunction(value) {
  console.log(value)
  return value
}
adiga
  • 34,372
  • 9
  • 61
  • 83
visizky
  • 701
  • 1
  • 8
  • 27
  • `secondFunction(firstFunction(ID))`. You can assign the returned value of the first function to a variable and pass it. – Ramesh Reddy Jul 11 '20 at 11:32
  • `firstFunction` looks to be sync function, so `secondFunction` WILL be executed after the first one returns! – Ahmed Hammad Jul 11 '20 at 11:33
  • Is it mandatory that second function will run ? – Harmandeep Singh Kalsi Jul 11 '20 at 11:33
  • 3
    What is the *"async call"*? Also, please go through [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) – adiga Jul 11 '20 at 11:42

2 Answers2

0

Save the return in to a variable and check if it is true-ish.

returnValue =  firstFunction(ID);
if (returnValue) {
    secondFunction(returnValue);
}

Though if you are really using this for logging, you might just send a null-value to the logger and make it discard values it doesn't need to log. That way you can change the log-verbosity in a single place.

Zsolt Szilagyi
  • 4,741
  • 4
  • 28
  • 44
0

You can store the returned value of the first function into a variable and then pass that variable to your second function. Something like this:

function Main(ID) {
   let value = firstFunction(ID);
   secondFunction(value)
}
Tomanator
  • 18
  • 5