I am trying to use Promises with my async functions. From my understanding promises are supposed to alleviate callback hell. However it seems my code is still very deeply nested.
Am I missing something about promises (could this be rewritten to be more readable/idiomatic) or do promises nest just like callbacks sometimes?
In this example I'm building a function that calls an API to retrieve a friends list from some social media account. If it the initial call fails due to authentication errors, I know I have to authenticate first and do the call again.
const myRequest = { /* custom instance of 'request-promise' */ }
function getFriendsList() {
return new Promise((resolve, reject) => {
myRequest.get('/getFriendList').then(resp => {
if (needsAuthentication(resp)) {
myRequest.post('/auth', credentials).then(() => {
myRequest.get('/getFriendList').then(resp => resolve(resp.body))
}).catch(err => {
reject(err)
})
} else {
resolve(resp.body)
}
}).catch(err => {
reject(err)
})
})
}
function authenticate() {
return new Promise((resolve, reject) => {
getCredentials().then(credentials => {
myRequest.post('/auth').then(resp => {
return resp.statusCode == '200' ? resolve(resp) : reject(resp)
})
}).catch(err => reject(err))
})
}