The scenario is like this, I get a get request and it triggers a function which returns a Promise (promise1
), and the Promise returning function itself has a chain of promises.
Now I do not want to wait for the chain to be over before sending the response to the front end, but want to resolve somewhere in the middle.
Now the rest of the question is put as a comment in the code, where it makes more sense.
app.get('/data', (req, res)=>{
promise1()
.then(result=>{
res.status(200).send({msg:result});
})
.catch(result=>{
res.status(400).send({msg:"Error"});
})
})
let promise1 = ()=>{
return new Promise((resolve, reject)=>{
promise2()
.then(result=>{
resolve(result);
/*What I want here is, just after the promise2 is resolved I want
to send the result back to the get router, so I can give quick response
and continue the slow processing in the backend which is promise3, but this
does not work as expected, I do not get the result in the router until promise3 is
resolved. But I do not want that. So any suggestions on how to achieve that.
*/
return promise3()
})
.then(result=>{
console.log("Done");
})
.catch(err=>{
console.log(err);
})
})
}
let promise2 = ()=>{
return new Promise((resolve, reject)=>{
resolve("Done");
})
}
let promise3 = ()=>{
return new Promise((resolve, reject)=>{
//Slow Async process
resolve("Done");
})
}
Was able to do this by putting promise3
in setTimeout
but I am not sure
if that is the correct way.
Please ignore any syntactical mistake, this is just to give the idea of the question.
Also, I am not sure if this is the correct way of doing this - correct me if I am wrong.