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
function looks like:
async anotherAsyncFunc (url) {
return await axios({
url,
}).then(res => res.data)
.catch(err => {
throw err;
});
}
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);
}
If it's not clear, I'm getting the file itself like normal, and appending a fileName to it, then resolving that object back.
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.
async
functions return promises. Nor can you turn a Promise-wrapped value into an ordinary value, you will always have toawait
or call.then
. Why did you expect to get an array? – FlotowPromise.all()
because I'm mapping over a dataset and returning the result of async function for each item. Thus creating an array. However, I just solved my own issue and am posting a solution now – ParaffinicPromise.all
returns a Promise. Again, you cannot 'unwrap' a promise. You can only.then
it. – FlotowFileRetriever.mainAsyncFunc(metadata).then(contents => ...)
, and with my new working codecontents
is an array. – Paraffinicawait
is sugar over.then
. You cannot ever unwrap a promise. Its a logical impossibility in the general case, as there is no way to tell if a promise is resolved or not. – Flotownew Promise
when the values you're working with are already promises, it usually means you've got something wrong. – Foreordain