如何从数组中提取Promise对象的值并使用——解决Promise.all中fetch请求返回Promise而非实际下载链接的问题
解决Promise.all中file字段返回Promise对象而非实际下载链接的问题
你的问题出在**map返回的数组里,每个对象的file字段是未被解析的Promise,但Promise.all只会等待数组中的Promise元素,不会自动解析对象内部的Promise**。所以最终得到的对象里file还是处于已完成状态的Promise,而不是实际的链接。
要解决这个问题,你需要让map的每个迭代项都返回一个Promise——这个Promise会先完成file对应的fetch请求,再解析为包含实际链接的完整对象。这样Promise.all就能等待所有这些Promise完成,最终得到你期望的数组结构。
修改后的代码如下:
fetch(`/books/${search}`) .then((res) => res.json()) .then(async (d) => { // 把map的回调改成async函数,让每个项返回一个Promise const withChildren = d.map(async (e) => { // 先等待file的fetch请求完成,拿到实际的下载链接 const fileHref = await fetch( `https://cloud-api.yandex.net:443/v1/disk/public/resources/download?public_key=${encodeURI( 'https://disk.yandex.ru/d/o9lNK0tpVCH7sQ' )}&path=${encodeURI(e.path)}` ) .then(res => res.json()) .then(res => res.href); // 返回包含实际链接的完整对象 return { name: e.name, size: bytes2Size(e.size), date: new Date(e.date).toLocaleDateString(), file: fileHref }; }); // 等待所有Promise完成,得到的res就是每个对象都包含实际file链接的数组 const resolvedBooks = await Promise.all(withChildren); setBooks(resolvedBooks); setIsLoaded(true); });
关键说明:
- 将
map的回调改为async函数后,map会返回一个Promise数组,每个Promise都会等待内部的fetch请求完成,再解析为你需要的对象。 Promise.all会等待这个数组里的所有Promise都完成,最终返回的resolvedBooks就是所有对象的file字段都已解析为实际链接的数组,你可以直接用这个结果更新状态。
内容的提问来源于stack exchange,提问作者sayinmehmet47
相关产品推荐
相关产品推荐

