Skip to content

Instantly share code, notes, and snippets.

@JavadocMD
Last active July 25, 2019 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JavadocMD/7a7530ce768206ce4baeaf21c40f6c80 to your computer and use it in GitHub Desktop.
Save JavadocMD/7a7530ce768206ce4baeaf21c40f6c80 to your computer and use it in GitHub Desktop.
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