-1

I need help with the layout of some code. Can I somehow call function3 with an argument from both function1 and function2? I can't make function2 to be a nested function since it is activated by a onclick.

Thank you!

function 1(){
//This function activates when a file is imported and calculates one variable from an imported document.
}
function 2(){
//The function activates from an "onclick()" this function calculates another variable.  
}
function 3(){
//calculation of the two variables
}
Vadim
  • 8,701
  • 4
  • 43
  • 50
WilliamG
  • 451
  • 1
  • 8
  • 16

3 Answers3

0

You can create two variables in the common functions' scope and check them. Something like this:

var firstVar = null;
var secondVar = null;

function fnc1(){
//This function activates when a file is imported and calculates one variable from an imported document.
    firstVar = importedVariable;
    if(secVar){
        fnc3();
    }
}
function fnc2(){
//The function activates from an "onclick()" this function calculates another variable.  
    secondVar = anotherVariable;
    if(firstVar){
        fnc3();
    }

}
function fnc3(){
//calculation of the two variables
    alert(firstVar + secondVar);
}
MysterX
  • 2,318
  • 1
  • 12
  • 11
  • the thing is i want to call function fc3 with two arguments. One from fnc1 and one from fnc2. I understand this isn't possible with my current code but i don't know how to solve it. Hope this made sens – WilliamG Dec 01 '16 at 15:57
0

You could use the Promise api to handle the asynchronous functions.

Also you cannot name a function starting with a number.

const element = document.querySelector('#click')

function one(arg) {
  return new Promise((resolve, reject) => {
    // get the file and pass the resolve function to it
    getTheFile(resolve)
  })
}
function two(arg) {
  return new Promise((resolve, reject) => {
    // bind your event inside the promise
    element.addEventListener('click', e => {         
      resolve(arg)
      console.log('click resolved')
    }, false)
  })
}

// callback when promises are resolved
function three([arg1, arg2]) {
  console.log('calc resolved', arg1 + arg2)
}


Promise.all([
  one(1),
  two(2)
]).then(three)

// ignore this
function getTheFile(resolve) {
  // get the file asynchronously
  setTimeout(() => {
    // get something from the file and pass it to resolve
    resolve(1)
    console.log('file resolved')
  }, 250)
}
<button id="click">Click</button>
synthet1c
  • 6,152
  • 2
  • 24
  • 39
0
function Handler() {
    this.foo = function(v) { this.a = v }
    this.bar = function(v) { this.b = v }
    this.baz = function() { return this.a + this.b }
}

h1 = new Handler()
h2 = new Handler()
h3 = new Handler()

h1.foo( 5 )
h1.bar( 6 )

h2.foo( 1 )
h2.bar( 2 )

h3.foo( 10 )
h3.bar( 20 )

print( h1.baz() )
print( h2.baz() )
print( h3.baz() )
shinobi
  • 351
  • 1
  • 8