Skip to content

Instantly share code, notes, and snippets.

@bearzk
Last active April 11, 2023 09:27
Show Gist options
  • Save bearzk/3d6e8d3690e1239d53bbbbeec0e480f9 to your computer and use it in GitHub Desktop.
Save bearzk/3d6e8d3690e1239d53bbbbeec0e480f9 to your computer and use it in GitHub Desktop.
async await non-blocking example

async await non-blocking

In the context of the node process that handles multiple http requests, async await is non-blocking. Though in each request, async await will block.

See this example, calling the 2 endpoints /fast and /slow, /slow will respond after 3 seconds, you can call the /fast at the same time multiple times and you will get a response immediately.

image

// system imports
// 3rd party imports
const express = require('express')
// local imports
const app = express()
const port = 3000
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
app.get('/fast', (req, res) => {
console.log('reached /fast')
res.send('Hello World!')
})
app.get('/slow', async (req, res) => {
const toSleep = 3000
await sleep(toSleep)
console.log('reached /slow')
res.send(`After ${toSleep}ms, Hello World!`)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
{
"name": "async-wait-non-blocking",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "[email protected]",
"license": "MIT",
"dependencies": {
"express": "^4.18.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment