Async/Await与Promise.all和.map函数无法正常工作
我正在使用大量的async
个函数,但遇到了一个奇怪的问题.
I have a slew of async
functions I'm using and I'm having a weird issue.
我的代码正常工作,如下所示:
My code, working, looks like:
async mainAsyncFunc (metadata) {
let files = metadata.map(data => this.anotherAsyncFunc(data.url));
return Promise.all(files);
}
anotherAsyncFunc
函数如下:
async anotherAsyncFunc (url) {
return await axios({
url,
}).then(res => res.data)
.catch(err => {
throw err;
});
}
当我尝试向第一个函数(mainAsyncFunc
)返回的内容追加更多数据时,出现了我的问题.我的想法是自然地在map
中做到这一点,当一切都说完之后,修改它就像:
My issue comes when I try to append more data to what the first function (mainAsyncFunc
) returns. My thoughts are to do that in the map
, naturally, and when all is said and done, modified it looks like:
async mainAsyncFunc (metadata) {
files = metadata.map(data => {
return new Promise((resolve) => {
let file = this.anotherAsyncFunc(data.download_url);
let fileName = data.name;
resolve({
file,
fileName
});
});
});
return Promise.all(files);
}
如果不清楚,我将像普通文件一样获取文件本身,并向其附加fileName,然后将该对象重新解析.
If it's not clear, I'm getting the file itself like normal, and appending a fileName to it, then resolving that object back.
由于某种原因,这将返回一个未决的Promise,而我希望它等待它们完成,然后以完整的文件和对象的名称返回.理解我在做什么的任何帮助将不胜感激.
For some reason, this is returning a pending Promise, whereas I would expect it to wait for them to be fulfilled and then returned as a complete file and name in an object. Any help understanding what I'm doing wrong would be greatly appreciated.
看起来您已经解决了问题,只需一点指针,就可以进一步简化代码,如下所示:
It looks like you've solved your issue, just as a bit of a pointer, you can further simplify your code as follows:
async anotherAsyncFunc (url) {
return (await axios({ url })).data;
}
async mainAsyncFunc (metadata) {
let files = metadata.map(async data => ({
file: await this.anotherAsyncFunc(data.download_url),
fileName: data.name
}));
return Promise.all(files);
}