0

I have two js files. In the first I use this code:

var rightsRef = db.collection("users").doc(uid).collection("rights");
        if(createDocumentWithoutId(rightsRef, "readGrades", "false", null, null, null, null) === true) {
          window.location.href = "../public/main/main_index.html";
        }
        else {

        }  

In the second js file, I use this code:

function createDocumentWithoutId(var databaseRef, var titleValue1, var contentValue1, var titleValue2, var contentValue2, var titleValue3, var contentValue3) {
  databaseRef.set({
    titleValue1: contentValue1,
    titleValue2: contentValue2,
    titleValue3: contentValue3,
  }).then(function() {
    return true;
  }).catch(function(error) {
    console.error("Error adding document: ", error);
    return false;
  });
}  

That I can call the function of the second js file I "import" both of them in the HTML file, by this way:

    <script type="text/javascript" src="javascript1.js"></script>
<script type="text/javascript" src="../javascript2_folder/javascript2.js"></script>

But I am getting this Error: ReferenceError: createDocumentWithoutId is not defined

marcelo.wdrb
  • 843
  • 1
  • 7
  • 14
  • 1
    The function doesn't exist until the second file is imported. Files are processed in the order they are included. – Taplar Nov 13 '18 at 18:15
  • 1
    Possible duplicate of [ReferenceError: function is not defined - JavaScript](https://stackoverflow.com/questions/13791248/referenceerror-function-is-not-defined-javascript) – Bill the Lizard Nov 13 '18 at 18:16
  • There also appears to be an issue with trying to use promise logic returning a value with other procedural logic. – Taplar Nov 13 '18 at 18:17
  • @Taplar What's wrong with the logic? And changing the order in the HTML did not help. – marcelo.wdrb Nov 13 '18 at 18:23
  • Ref. https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call This link talks about ajax being asynchronous, but you can ignore that part. Both ajax, and your logic, use promises (an action followed by a `then()` callback) – Taplar Nov 13 '18 at 18:23

2 Answers2

0

You first JS file is being fully executed before the second one. That's what's causing your error - the function in the second file hasn't been loaded yet. You could reverse the order that they're define in your HTML so that the function is defined before it's called.

Doug Stevenson
  • 236,239
  • 27
  • 275
  • 302
0

JS files execute when they're loaded, and in this case execution includes defining the functions. Try reversing the load order of your files, or putting some sort of check on the first code, such as this:

function amIDependentOnAnotherFile(){
  if (typeof functionInAnotherFile == 'undefined')
   return setTimeout(amIDependentOnAnotherFile, 5);
  doSomething();
}
Andrew Ridgway
  • 563
  • 2
  • 9