Reputation: 27537
I have code that basically looks like this:
return Promise.all([
myPromise("foo", () => saveToFirebase("foo")),
myPromise("bar", () => saveToFirebase("bar")),
... // 50 more of these ^
]).then(() => {
res.status(200).send('ok');
}).catch(err => {
console.log(err.stack);
res.status(500).send('error');
});
My request times out because some of my requests take a long time. My question is: if I just called res.status(200)
without chaining it Promise.all
, would my unresolved promises still resolve even after a response is sent? Or would all execution of my code stop once a response is sent?
Like this:
Promise.all([
myPromise("foo", () => saveToFirebase("foo")),
myPromise("bar", () => saveToFirebase("bar")),
... // 50 more of these ^
])
res.status(200).send('ok');
Upvotes: 0
Views: 60
Reputation: 436
The promise will always be executed. As you can see in following picture after response is send after promise resolve
is printed on console.
And you can also keep the connection alive by setting res.shouldKeepAlive
to true like this :
Promise.all([
check(2),
check(2),
check(2)
]).then(() => {
console.log('after promise resolve');
setTimeout(function() {
res.send('done');
}, 10000);
});
console.log('Before promise resolve');
res.shouldKeepAlive = true;
Upvotes: 1
Reputation: 51901
All promises will be either resolved or rejected. Express does not stop any execution when you finish request. You can try it out by simple console log:
Promise.all([
myPromise("foo", () => saveToFirebase("foo")),
myPromise("bar", () => saveToFirebase("bar")),
... // 50 more of these ^
])
.then(() => console.log("promises resolved"))
.catch(err => console.error("promises rejected", err))
res.status(200).send('ok')
However with this approach you don't know if anything went wrong when sending response.
Upvotes: 1
Reputation: 138457
Alternatively you could keep the connection alive like this:
const keepalive = setInterval(_=>res.write("."),1000);
return Promise.all([
myPromise("foo", () => saveToFirebase("foo")),
myPromise("bar", () => saveToFirebase("bar")),
... // 50 more of these ^
]).then(() => {
res.status(200).send('ok');
}).catch(err => {
console.log(err.stack);
res.status(500).send('error');
}).then(_=>clearInterval(keepalive));
Upvotes: 0