代码之家  ›  专栏  ›  技术社区  ›  Jeaf Gilbert

响应本机等待所有映像预取完成

  •  1
  • Jeaf Gilbert  · 技术社区  · 6 年前

    我试图在导航到另一个屏幕之前预取多个图像,但返回的学生都没有定义。

    prepareStudentImages = async (students) => {
        let returnedStudents = students.map(student => {
            Image.prefetch(student.image)
            .then((data) => {
                ...
            })
            .catch((data) => {
                ...
            })
            .finally(() => {
                return student;
            });
        });
    
        await console.log(returnedStudents); // ----> all items undefined
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Matt Way    6 年前

    有几个问题需要解决:

    1)你的 map() 函数不返回任何内容。这就是为什么您的控制台日志是 undefined .

    2)一旦您的映射函数正常工作,您将记录一系列承诺。要处理多个承诺(数组),可以使用 Promise.all() .

    所以我认为要解决这个问题,你可以:

    prepareStudentImages = async (students) => {
      const returnedStudents = students.map(student => 
        Image.prefetch(student.image)
          .then((data) => {
              ...
          })
          .catch((data) => {
              ...
          })
          .finally(() => {
              return student
          })
      )
    
      console.log(returnedStudents) // log the promise array
    
      const result = await Promise.all(returnedStudents) // wait until all asyncs are complete
      console.log(result) // log the results of each promise in an array
    
      return result
    }