you can chain them and avoid the nesting. Anything a .then handler returns becomes the value of the next one like this:
fetch(url)
.then((response) => response.json())
.then((json) => {
// do stuff
})
Promises will wait until resolved, normal values will call the next handler "right away" (there's some nuance here and some edge cases about what "right away" means, but for the most part you never need to think about that)
And if you want to do more things and handle errors, it becomes pretty simple as well:
fetch(url)
.then((response) => response.json())
.then((json) => {
if (!json.user.id) {
throw new Error('user id not found')
} else {
return db.sql('SELECT * from users where id = $1', [json.user.id])
}
}).then((user) => {
return response.send(user)
}).catch((err) => {
// any error thrown at any point during the chain will trigger this catch
return response.error(err)
})
I still completely agree that async/await is still better in this case, but then throw some more wrenches into the situation like wanting to handle multiple promises at a time and you start to see where using "raw promises" really comes in handy. Like this:
try {
const res = await fetch(url)
const json = await res.json()
if (!json.user.id) {
throw new Error('user id not found')
}
const [ userObj, userAuthLevel, someOtherStuff] = await Promise.all([
db.sql('SELECT * from users where id = $1', [json.user.id]),
db.sql('SELECT * from otherStuff where userId = $1', [json.user.id]),
fetch('https://other.stuff/and/things')
])
return response.send({
userObj,
userAuthLevel,
someOtherStuff
})
} catch (err) {
return response.error(err)
}
or say there's an expensive call that you can start BEFORE the first fetch, but still need to wait on later (ignoring most other stuff for simplicity):
// notice there's no await...
// we can kick off the request now, but not wait for the result until later
const someOtherStuffPromise = fetch('https://other.stuff/and/things')
const res = await fetch(url)
const json = await res.json()
// do other things here
// finally wait for the promise to resolve here.
const someOtherStuff = await someOtherStuffPromise