1

Hello I'm having a little problem when I try to assign returned value from function into a variable. I've tried this code with a console.log and it displays the right result but when I want to assign this result to a variable it gives undefined value. So here is the code and can u explain it to me what am I doing wrong because I'm a javascript noobie.

const onDataChange = (items) => {
   let products = [];
   let images = listFromStorage();
   //a function call that displays undefined value but should return array
   console.log(images);
   items.forEach((item) => {
       let key = item.key;
       let data = item.val();
       products.push({
           key : key,
           title : data.title,
           before : data.before,
           after : data.after
       })
   })
   setProductList(...productList, products);
}

const listFromStorage = () => {
let storageRef = firebaseService.getStorage().ref().child('/posts/products');
let images = [];
storageRef.listAll().then(function (res) {
    res.items.forEach((imageRef) => {
      imageRef.getDownloadURL().then((url) => {
          images.push({
            url : url
          });
      });
    });
    return images;
  })
  .catch(function (error) {
    console.log(error);
  });

}

1 Answer 1

2

You need to not only wait for the asynchronous code to finish, but you need to also return a value from listFromStorage to assign.

const onDataChange = async (items) => { // <-- declare async
  const products = [];
  const images = await listFromStorage(); // <-- await result
   
  console.log(images);
  items.forEach((item) => {
    const key = item.key;
    const data = item.val();
    products.push({
      key: key,
      title: data.title,
      before: data.before,
      after: data.after
    })
  })
  setProductList(...productList, products);
}

const listFromStorage = () => {
  const storageRef = firebaseService
    .getStorage()
    .ref()
    .child('/posts/products');
  const images = [];
  return storageRef // <-- return Promise chain
    .listAll()
    .then(function (res) {
      res.items.forEach((imageRef) => {
        imageRef.getDownloadURL().then((url) => {
          images.push({ url });
        });
      });
      return images;
    })
    .catch(function (error) {
      console.log(error);
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that little mistake was really bugging me and it was very simple and precise answer from you with some code clean up :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.