简体   繁体   中英

jQuery function is not available in Promise.then()

I am implementing a threaded comment board on my website with this jQuery library .

Here is a part of my index.html where comment data are downloaded from Firebase and displayed in the front end through the library.

For an experiment, I tried to display a comment board in an element (eg body ). In the first code below, it does not throw any error. However, this is not the right place to call the comment board function because the function has to use the data from Firebase.

So, I moved the jQuery function to the then method of db.collection (second code) so that the comment function can all the data from Firebase (stored in querySnapshot ).

Then the second one throws the error

Uncaught (in promise) TypeError: $(...).comments is not a function

Why is this happening? How can the jQuery function correctly use the data from Firebase?


First code

<script>
window.onload = () => {
  $("body").comments({
    profilePictureURL: 'sample-icon.png',
    getComments: (success, error) => {
      var commentsArray = [{
          ...
      }];
      success(commentsArray);
    }
  });
  const db = firebase.firestore()
  db.collection("projects").get().then(querySnapshot => {
   ...
  })
}
</script>

Second code

<script>
window.onload = () => {
  const db = firebase.firestore()
  db.collection("projects").get().then(querySnapshot => {
    $("body").comments({
      profilePictureURL: 'sample-icon.png',
      getComments: (success, error) => {
        var commentsArray = [{
          ...
        }];
        success(commentsArray);
      }
    });
  })
}
</script>

Here is a part of the file structure of my website

/public        <--- Hosting on Firebase
  index.html
  /forum
    index.html <--- the index.html shown in the question above
  /css
    jquery-comment.css <--- from the jQuery library
  /js
    jquery-comment.js <---  from the jQuery library

 <script> window.onload = () => { const db = firebase.firestore() // use a closure const jq = $; db.collection("projects").get().then(querySnapshot => { jq("body").comments({ profilePictureURL: 'sample-icon.png', getComments: (success, error) => { var commentsArray = [{... }]; success(commentsArray); } }); }) } </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM