【问题标题】:Assigned returned value from function chain into a variable in javascript将函数链的返回值分配给javascript中的变量
【发布时间】:2021-10-22 21:34:30
【问题描述】:

您好,当我尝试将函数的返回值分配给变量时,我遇到了一个小问题。我已经用 console.log 尝试了这段代码,它显示了正确的结果,但是当我想将此结果分配给一个变量时,它给出了未定义的值。所以这是代码,你能向我解释一下我做错了什么,因为我是一个 JavaScript 新手。

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

}

【问题讨论】:

    标签: javascript arrays reactjs promise


    【解决方案1】:

    你不仅需要等待异步代码完成,还需要从listFromStorage返回一个值来赋值。

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

    【讨论】:

    • 谢谢你,那个小错误真的让我很烦,你的回答非常简单而准确,清理了一些代码:)
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多