google-auth-library-nodejs
google-auth-library-nodejs copied to clipboard
Refactoring: Quit mixing Promises and async/await
Problem
- There is a comment by @bcoe that says
TODO
. This comment has been here for two years.- https://github.com/googleapis/google-auth-library-nodejs/blob/main/src/auth/googleauth.ts#L206-L232
Suggestion
- It would be better to use
async/await
only and reduce the length of code. It will make this repo easier to see through. - I am going to create PR when this change is accepted but beforehand, I put my plan below. Please use these code for your decision.
Before
// TODO: refactor the below code so that it doesn't mix and match
// promises and async/await.
this._getDefaultProjectIdPromise = new Promise(
// eslint-disable-next-line no-async-promise-executor
async (resolve, reject) => {
try {
const projectId =
this.getProductionProjectId() ||
(await this.getFileProjectId()) ||
(await this.getDefaultServiceProjectId()) ||
(await this.getGCEProjectId()) ||
(await this.getExternalAccountClientProjectId());
this._cachedProjectId = projectId;
if (!projectId) {
throw new Error(
'Unable to detect a Project Id in the current environment. \n' +
'To learn more about authentication and Google APIs, visit: \n' +
'https://cloud.google.com/docs/authentication/getting-started'
);
}
resolve(projectId);
} catch (e) {
reject(e);
}
}
);
}
After
this._getDefaultProjectIdPromise = (async () => {
const projectId =
this.getProductionProjectId() ||
(await this.getFileProjectId()) ||
(await this.getDefaultServiceProjectId()) ||
(await this.getGCEProjectId()) ||
(await this.getExternalAccountClientProjectId());
this._cachedProjectId = projectId;
if (!projectId) {
throw new Error(
'Unable to detect a Project Id in the current environment. \n' +
'To learn more about authentication and Google APIs, visit: \n' +
'https://cloud.google.com/docs/authentication/getting-started'
);
}
return projectId;
})();
}
This looks good to me, as long as tests pass as well :) Thank you!
Thank you. I am going to create PR 👍
Fixed in https://github.com/googleapis/google-auth-library-nodejs/pull/1436