简体   繁体   中英

Assigned returned value from function chain into a variable in javascript

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

}

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

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