A loop stops the execution of a route on Express JS until it finishes, this can generate a timeout in the browser.
In the example it takes approx. 10 seconds to show the website (I need to execute the sleep function) , but I would like this for you to continue running on Background, and the route will be displayed immediately
Any suggestion?
app.get('/', function(req, res) {
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let array = [1,2,3,4,5,6,7,8,9]
for (const a of array) {
console.log(a)
await sleep(1000);
}
res.send('hello world');
});
CodePudding user response:
Remove the await keyword in the for loop. The await keywords basically stops the code from executing until the current Promise is resolved, so if you dont await on it, it runs alongside other pieces of code. Your response is returned in less than a second, while the node process resolves the sleep promise in the background
app.get('/', function(req, res) {
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let array = [1,2,3,4,5,6,7,8,9]
for (const a of array) {
console.log(a)
// await sleep(1000);
sleep(1000);
}
res.send('hello world');
});
CodePudding user response:
If you want the response send immediately, then put the res.send()
BEFORE your loop. You can still run code after you've sent the response - that code just can't be involved in computing what the response will be because it will have already been sent.
app.get('/', function(req, res) {
res.send('hello world');
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let array = [1,2,3,4,5,6,7,8,9]
for (const a of array) {
console.log(a)
await sleep(1000);
}
});