0
const express = require('express')
const app = express()

app.get('/', (req, res) => {
   res.send("helo")
});
app.post('/',  (req, res) => {

    console.log('served');
    name(res);
});
async function name(res) {
    console.log('waiting')
    var waitTill = new Date(new Date().getTime() + 10 * 1000);
    while(waitTill > new Date()){}
    res.send('ok');
    console.log('out of waiting')
}
app.listen(3000, () => console.log('Example app listening on port 3000!')) 

Simply: Server not behaving asyncronously

Explanation: here's the code, now there's a wait of 10 seconds in name function. As I know, if a client comes and it stucks on wait. another client shouldn't be effected. But in my code, the second client had to wait until the first client is catered.

0

1 Answer 1

2

async functions don't work like this. They need promises to work correctly. Synchronous code (like the painful while(waitTill > new Date())) will still be synchronous. In Node, it's actual quite hard to block the event loop without doing crazy stuff like long running while loops. Almost all things that take time are designed to be asynchronous, so you don't generally encounter this problem.

To use an async function you need something that returns a promise. For example if we make a version of wait that uses setTimeout wrapped in a promise, then you shouldn't have this problem of the event loop blocking.

// a more realistic function that takes `time` ms
const wait = time => new Promise(resolve => setTimeout(resolve, time))

app.post('/',  (req, res) => {
    console.log('served');
    name(res);
});
async function name(res) {
    console.log('waiting')
    await wait(10 * 1000) // await expects wait to return a promise
    res.send('ok'); // will send 10 seconds later without blocking the thread
    console.log('out of waiting')
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.