0

I can't access snapshot value outside promises. I have these functions

function getAuthorData() {
  metadataRef
    .child("author")
    .on("value", (snap) => {
      return snap.val()
    })
}

function getSiteSocialLinks() {
  metadataRef
    .child("social")
    .on('value', (snap) => {
      return snap.val();
    })
}

function getFeaturedPosts() {
  featuredRef.on('value', (snap) => {
    return snap.val();
  })
}

function getBlogPosts() {
  blogPostsRef
  .orderByChild('createOn')
  .on('value', (snap) => {
    return snap.val()
  });
}

function getPostCategories() {
  postRef
  .child('categoryStats')
  .on('value', (snap) => {
    return snap.val();
  });
}

function getTotalPostsLength() {
  postRef
  .child('nopp')
  .on('value', (snap) => {
    return snap.val();
  })
}

and when I try this

var ourPosts = getBlogPosts()
  var ourCategories = getPostCategories()
  var totalnumOfPosts = getTotalPostsLength()

  console.log(`Our post: ${ourPosts}\n our categories: ${ourCategories}\n total number of posts: ${totalnumOfPosts}\n`)

this is what I get

Our post: undefined our categories: undefined total number of posts: undefined

I dont really know if it has anything to do with scope. Please help

Jalasem
  • 27,261
  • 3
  • 21
  • 29

1 Answers1

0

You are not using Promises as you should.

Try this:

getBlogPosts().then(value => {
  console.log(value);
});

getPostCategories().then(value => {
  console.log(value);
});

getTotalPostsLength().then(value => {
  console.log(value);
});

And add a return before each metadataRef, something like:

function getAuthorData() {
  return metadataRef
    .child("author")
    .on("value", (snap) => {
      return snap.val()
    })
}

function getSiteSocialLinks() {
  return metadataRef
    .child("social")
    .on('value', (snap) => {
      return snap.val();
    })
}

function getFeaturedPosts() {
  return featuredRef.on('value', (snap) => {
    return snap.val();
  })
}

function getBlogPosts() {
  return blogPostsRef
  .orderByChild('createOn')
  .on('value', (snap) => {
    return snap.val()
  });
}

function getPostCategories() {
  return postRef
  .child('categoryStats')
  .on('value', (snap) => {
    return snap.val();
  });
}

You may need to read a little bit about "why promises exists", so you'll understand why you need to use it in this way.

Broda Noel
  • 1,760
  • 1
  • 19
  • 38