const processInboundEmailAttachment = async (files: any[]): Promise<any[]> => {
const attachments = []
await Promise.all(
files.map(async (file) => {
try {
let response = null
response = await axios.get(file.url, {
headers: {
Accept: "message/rfc2822"
},
auth: {
username: "api",
password: "api-key"
},
responseType: "stream"
})
if (response && response.data) {
response.data.pipe(concat(async data => {
try {
const mediaUrl = await uploadToFirestore(file["content-type"], data, file.name)
attachments.push({
name: file.name,
url: mediaUrl,
id : uuidv4()
})
} catch (error) {
console.log("err", error);
}
}));
}
} catch (err) {
log.error(err)
}
})
)
return attachments // from here this return initial attachments [] array
}
const uploadAttachment = async () => {
const attachment = await processInboundEmailAttachment(JSON.parse(attach))
console.log("attachment",attachment);
// I want updated pushed attachment array here but I got [] initial decalare value
}
app.get("/uploadAttachment", uploadAttachment)
In attachment console log I got [] array , It's return initial assign values of array. It's not wait for API response and newly pushed array.
I think There Is an some issue in Promise , It's not wait for updated array , It's return directly initialy attachment array
Thank you for Help In advnace
Looks like it is not waiting for uploadFirestore
response. You can cut down your function something like below and wrap it custom promise
.
const processInboundEmailAttachment = async (files: any[]): Promise<any[]> => {
const getFileUploadedResult = function(file) {
return new Promise(async (resolve, reject) => {
try {
let response = null
response = await axios.get(file.url, {
headers: {
Accept: "message/rfc2822"
},
auth: {
username: "api",
password: "api-key"
},
responseType: "stream"
})
if (response && response.data) {
response.data.pipe(concat(async data => {
try {
const mediaUrl = await uploadToFirestore(file["content-type"], data, file.name)
resolve({
name: file.name,
url: mediaUrl,
id : uuidv4()
})
} catch (error) {
reject(err)
}
}));
}
} catch (err) {
log.error(err)
reject(err)
}
})
}
return Promise.all(
files.map(async (file) => {
return getFileUploadedResult(file)
})
)
}
const uploadAttachment = async () => {
const attachment = await processInboundEmailAttachment(JSON.parse(attach))
console.log("attachment",attachment);
// I want updated pushed attachment array here but I got [] initial decalare value
}
app.get("/uploadAttachment", uploadAttachment)