I have a POST
API with some logic inside of it as below :
app.post('/', async (req: Request, res: Response) => {
const tasksRequest = req.body as TasksRequest;
let tasks: Promise<any>[] = []
tasks = tasksRequest.tasks.map((t) => processTask(t, tasksRequest.configs));
await Promise.all(tasks);
});
and below is the processTask
function :
function processTask(task: Task, configs: Configs) {
return new Promise<void>((resolve, reject) => {
try {
const fileName = './output/' + task.tag + 's.json';
fetch(configs.Host + configs.APIsBasePrefix + task.parentResource + task.mostRelatedPath, {
method: 'GET'
}).then(result => {
result.json().then(jsonResult => {
fs.writeFile(fileName, JSON.stringify(jsonResult), function () {
console.log('finished writing :' + fileName);
resolve();
});
}).catch(err => reject(err));
}).catch(err => reject(err));
} catch (err) {
console.log(err);
}
});
}
The issue is that I'm not able to make my server wait for all the promises to finish before sending the response back using the await Promise.all(tasks);
I tried many things and that was my latest approach.. Is there anything I'm missing?
Thanks in advance!
Changing my implementation many times, used libraries like fs.promise but with no luck.
UPDATE :
I tried also the below to make the code more readable :
app.post('/', (req: Request, res: Response) => {
const tasksRequest = req.body as TasksRequest;
let tasks = []
tasks = tasksRequest.tasks.map( (t) => processTask(t, tasksRequest.configs));
//const temp = (processTask(tasksRequest.tasks[0],tasksRequest.configs));
console.log(tasks);
Promise.all(tasks).then(res=>{
console.log('After awaiting');
});
});
async function processTask(task: Task, configs: Configs) {
try {
const fileName = './output/' + task.tag + 's.json';
const result = await fetch(configs.Host + configs.APIsBasePrefix + task.parentResource + task.mostRelatedPath, {
method: 'GET'
});
const jsonResult = await result.json();
return fs.promises.writeFile(fileName, JSON.stringify(jsonResult));
} catch (err) {
console.log(err);
}
}