【问题标题】:The function should be callable该函数应该是可调用的
【发布时间】:2018-11-13 18:12:51
【问题描述】:

我有两个 js 文件。在第一个我使用这个代码:

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 {

        }  

在第二个js文件中,我使用了这段代码:

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;
  });
}  

我可以调用第二个js文件的函数,我将它们都“导入”到HTML文件中,通过这种方式:

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

但我收到此错误: ReferenceError: createDocumentWithoutId is not defined

【问题讨论】:

  • 在导入第二个文件之前该函数不存在。文件按照包含的顺序进行处理。
  • 尝试使用 Promise 逻辑返回值与其他过程逻辑似乎也存在问题。
  • @Taplar 逻辑有什么问题?并且更改 HTML 中的顺序并没有帮助。
  • 参考。 stackoverflow.com/questions/14220321/… 这个链接谈到 ajax 是异步的,但你可以忽略那部分。 ajax 和您的逻辑都使用承诺(一个动作后跟一个then() 回调)

标签: javascript html function google-cloud-firestore


【解决方案1】:

您的第一个 JS 文件在第二个之前被完全执行。这就是导致您的错误的原因 - 第二个文件中的函数尚未加载。您可以颠倒它们在 HTML 中定义的顺序,以便在调用函数之前定义函数。

【讨论】:

  • 更改 HTML 中的加载顺序并没有解决我的问题。
【解决方案2】:

JS 文件在加载时执行,在这种情况下执行包括定义函数。尝试颠倒文件的加载顺序,或对第一个代码进行某种检查,例如:

function amIDependentOnAnotherFile(){
  if (typeof functionInAnotherFile == 'undefined')
   return setTimeout(amIDependentOnAnotherFile, 5);
  doSomething();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 2012-10-30
    • 2019-01-01
    • 2012-07-11
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多