I am trying to get files from the function getPageFiles
, but only after the two axios post commands are done, on the success of the second axios, return the file object. I am not sure why files are a Promise instead of a list of objects?
async function getPageFiles() {
return connectionInfo.files.map(
(file) => {
return axios
.post(
API_ROUTE,
{
file_name: file.file_name,
},
{
headers: {
"Content-Type": "application/json",
authorization,
},
params: { presignedUrl: true },
}
)
.then((response: any) => {
const res = JSON.parse(response);
// PUT request: upload file to S3
return axios
.put(res.uploadURL, file.binary)
.then((s3Response: TResponseError | any) => {
return {
file_type: "csv",
s3_path: `s3://${process.env.TEST}/${file.file_name}`,
table_name: file.table_name.toUpperCase(),
}
}
})
.catch((error) => {
// eslint-disable-next-line no-console
console.error(`Error putting file to s3 upload URL: ${error}`);
});
});
}
);
};
let files = await getPageFiles();
CodePudding user response:
The problem is that you aren't actually waiting for the promises inside the array to resolve. You're currently doing something like this:
(async () => {
const result = await Promise.resolve([
new Promise((resolve) => setTimeout(resolve, 500, 1)),
new Promise((resolve) => setTimeout(resolve, 500, 2)),
new Promise((resolve) => setTimeout(resolve, 500, 3)),
]);
// trying to use the resulting array of numbers
console.log(result.map((x) => x * 2));
})();
See how NaN
is logged instead of 2
, 4
, 6
? That's because in this example, x
is still a promise that hasn't been resolved, so you can't use it like a number. You probably meant to use Promise.all
which return a new promise that resolves when all the promises in the array resolve:
(async () => {
const result = await Promise.all([
new Promise((resolve) => setTimeout(resolve, 500, 1)),
new Promise((resolve) => setTimeout(resolve, 500, 2)),
new Promise((resolve) => setTimeout(resolve, 500, 3)),
]);
// trying to use the resulting array of numbers
console.log(result.map((x) => x * 2));
})();
So how would it look like in your code? Well, just wrap your map:
async function getPageFiles() {
return Promise.all(connectionInfo.files.map((files) => {
// ...
}));
}