People say that async/await is just another way to write callbacks and promises. However, I feel as though they are not interchangeable; in fact, callbacks would be better in Express because it returns the result to the user right away. Is this correct?
In the following example, let's say we don't care about the result of doSomethingAsync(), but want to redirect right away. Here, we use await.
router.get('/register', async (req, res) => {
res.redirect('/')
await doSomethingAsync()
console.log(1)
}
router.get('/', (req, res) => {
console.log(2)
...
}
This would print out 1, then 2, meaning that we won't be able to exit the /register handler and redirect unless the async function finishes.
In the below version, we use a promise with a 'then' function.
router.get('/register', (req, res) => {
res.redirect('/')
doSomethingAsync().then(() => {
console.log(1)
}
}
router.get('/', (req, res) => {
console.log(2)
...
}
This would print out 2, then 1, meaning that we can exit immediately and redirect the user. Isn't the second way better for performance? Or are they actually the same?
Aucun commentaire:
Enregistrer un commentaire