Skip to content

Instantly share code, notes, and snippets.

@JavadocMD
Last active Jul 25, 2019
Embed
What would you like to do?
Possible optional chaining gains?
// Without optional chaining.
export const getInstance = async (instanceId: string): Promise<Instance> => {
const result = await ec2Client
.describeInstances({ InstanceIds: [instanceId] })
.promise()
if (!result.Reservations) {
throw new Error(`Could not find instance ${instanceId}`)
}
if (result.Reservations.length > 1) {
throw new Error('Found more than one reservation.')
}
const r = result.Reservations[0]
if (!r.Instances) {
throw new Error('Reservation contained no instances.')
}
if (r.Instances.length > 1) {
throw new Error('Found more than one instance.')
}
return r.Instances[0]
}
// With optional chaining?
export const getInstance = async (instanceId: string): Promise<Instance> => {
const result = await ec2Client
.describeInstances({ InstanceIds: [instanceId] })
.promise()
const instance = result.Reservations?.[0]?.Instances?.[0]?
if (!instance) {
throw new Error(`Could not find instance ${instanceId}`)
}
return instance
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment