I have two functions that manage Facebook login/logout on my front-end using promises. I am interested in refactoring them with async/await
.
The original code utilizing promises is as follows:
export function login() {
return new Promise<facebookSdk.IAuthResponse>((resolve, reject) => {
FB.login((response) => {
if (response.authResponse) {
resolve(response)
} else {
reject(errors.facebookLoginError)
}
})
})
}
export function logout() {
return new Promise<facebookSdk.IAuthResponse>((resolve) => {
FB.logout((response) => {
resolve(response)
})
})
}
Below is the modified version of these functions using async/await
:
function promiseFacebookLogin(): Promise<facebookSdk.IAuthResponse | Error> {
return new Promise<facebookSdk.IAuthResponse>((resolve, reject) => {
FB.login((response) => {
if (response.authResponse) {
resolve(response)
} else {
reject(errors.facebookLoginError)
}
})
})
}
export async function login(): Promise<facebookSdk.IAuthResponse | Error> {
try {
return await promiseFacebookLogin()
} catch (err) {
throw err
}
}
export async function logout(): Promise<facebookSdk.IAuthResponse | void> {
try {
return await FB.logout((response) => {
return response
})
} catch (err) {
throw err
}
}
The updated code now operates as intended, but there is a lingering question regarding the login
function. While I was able to eliminate the use of Promises entirely in the logout
function, for the login
function, I had to keep the Promise syntax and wrap it separately before awaiting the result. Upon researching, it seems this approach is typical for dealing with callback-based functions.
Is there anyone who can offer insights into why it isn't feasible to completely remove the Promise syntax from the login
function?