Can you move the definition of this function out of the then() clause? I think it'll make this block of code easier to read.