Closed bnb closed 7 years ago
Just wanted to point out something that was confusing in your express example:
app.get('/', async (request, response) => {
// awaiting Promises
const result = await getContent()
return result
})
In this example, nothing gets sent, you still need to call response.send(result)
. The other thing is that if getContent()
returns a rejected Promise, express won't handle the error, and the request will just hang. If you want to use async/await, this is what your middleware would have to look like:
app.get('/', async (request, response, next) => {
try {
// awaiting Promises
const result = await getContent()
response.send(result)
} catch (err) {
next(err)
}
})
Or you could write a higher-order-function to wrap your middleware to make it work like you presented (which isn't built into express out of the box):
const wrapAsync = (middleware) => {
return async (req, res, next) => {
try {
// Note that we don't `res.send` in here, the middleware should probably still
// control whether or not it responds to the client.
await middleware(req, res, next)
} catch (err) {
next(err)
}
}
}
app.get('/', wrapAsync(async (request, response) => {
// awaiting Promises
const result = await getContent()
response.send(result)
}))
I put this whenever I just need to simulate, or actually want to delay execution.
const delay = ms => new Promise(r => setTimeout(r, ms));
const timeout = (ms, message) => new Promise((_, rej) => reject(new Error(message)));
...
// timing out (doesn't cancel the original whatIWant() though
Promise.race([whatIWant(), timeout(1000, "too long dude!")]);
Another thing, although request-promise
has a simpler interface, I really wish more articles would use node-fetch (or isomorphic-fetch) for their request examples.
Adds NodeSource to the "Companies helping with Node.js security" section of
nodejs-security-overview.md