Thursday, 11 May 2017

Nested .then()'s Promises

I'm having some difficulty in simplifying the readability of the code I have written, so far I have managed to separate the code into two primary functions, however I'm still suffering with nested .then()'s. I'm not sure if there is any simpler way of writing these two functions. Any advice on structure and pointers in the right direction would be really appreciated.

function createHorseEntities( raceEntity ) {
    promises = horsePostHandler.init(raceEntity, race.Horse)
    _.each(promises, function( promise ){
        promise.then(function( entity ){
            if ( raceEntity.horses.length === 0 ) {
                controller.update({ "horseUpdate": true, "horseEntity": entity }, raceEntity)
            }
        })
    })
    return raceEntity
}
function init( object ) {
    handler.data = object.data.PARaceCardObject ? object.data.PARaceCardObject : object.data.PABettingObject;
    racePromises = _.map(handler.data.Meeting.Race, function( race ) {
        return Promise.all([ getMeeting(object.promise), controller.find({ x_reference: race.ID }) ])
        .spread(function( meetingEntity, raceEntity ) {
            return doesRaceExist(meetingEntity, raceEntity, race)
        })
        .then(createHorseEntities)
        .catch(errorHandler)
    })
    return racePromises
}



via CBainbridge