如何解决得到Promise <fullfield>作为回报
我要在数组中添加一堆承诺
const apiCallsToMake = [];
apiCallsToMake.push(this.getDataFromUnsplash(copyInputParams));
apiCallsToMake.push(this.getDataFromPexels(copyInputParams));
apiCallsToMake.push(this.getDataFromPixabay(copyInputParams));
return Promise.all(apiCallsToMake).then((response) => response);
我的getDataFromUnsplash看起来像这样
async getDataFromUnsplash(params: UNSPLASH): Promise<IMAGE_RESPONSE> {
try {
const { data } = await axios.get(`${upload_base_url}/search/photos`,{
params,});
const { results } = data;
const images = await results.map(async (image: any) => {
const imgData = {
id: image.id,url: image.urls.raw,};
if (this.includeBlob) {
const image_blob = await fetch(image.urls.raw).then(r => r.blob());
return { ...imgData,image_blob }
}
return imgData
});
return { name: "unsplash",images };
} catch (error) {
console.error(error);
return { name: "unsplash",error };
}
}
IMAGE_RESPONSE的类型为
export interface IMAGE_DATA {
width: number;
height: number;
url: string;
name: string;
id: string;
siza_small_url: string;
image_blob?: Blob
}
export interface IMAGE_RESPONSE {
name: SERVICENAME;
images?: Array<IMAGE_DATA>;
error?: any;
}
当我从romise.all(apiCallsToMake).then((response) => response);
收到console.log数据时,我得到了承诺,即
images: (10) [Promise,Promise,Promise]
name: "unsplash
或
Promise {<fulfilled>: {…}}
1: Promise {<fulfilled>: {…}}
2: Promise {<fulfilled>: {…}}
3: Promise {<fulfilled>: {…}}
4: Promise {<fulfilled>: {…}}
5: Promise {<fulfilled>: {…}}
6: Promise {<fulfilled>: {…}}
7: Promise {<fulfilled>: {…}}
8: Promise {<fulfilled>: {…}}
9: Promise {<fulfilled>: {…}}
有人可以告诉我为什么发生这种情况以及如何解决此问题吗?
解决方法
由于您的地图返回的是诺言数组,因此您需要在下一阶段将它们解包
async getDataFromUnsplash(params: UNSPLASH): Promise<IMAGE_RESPONSE> {
try {
const { data } = await axios.get(`${upload_base_url}/search/photos`,{
params,});
const { results } = data;
const imagePromises = results.map(async (image: any) => {
const imgData = {
id: image.id,url: image.urls.raw,};
if (this.includeBlob) {
const image_blob = await fetch(image.urls.raw).then(r => r.blob());
return { ...imgData,image_blob }
}
return imgData
});
const images = await Promise.all(imagePromises)
return { name: "unsplash",images };
} catch (error) {
console.error(error);
return { name: "unsplash",error };
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。