我试图在导航到另一个屏幕之前预取多个图像,但返回的 Students 都未定义。
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) 你的 map()
函数不返回任何东西。这就是为什么您的控制台日志是 undefined
的原因。
2) 一旦您的 map 函数起作用,您就会记录一组 promise 。要处理多个 promise (数组),您可以使用 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
}
关于javascript - React Native 等待所有图像预取完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54060668/