I have two functions that handle Facebook login/logout on my front-end and both of them are written with promises. I want to rewrite these using async/await
.
The original code with promises:
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)
})
})
}
Here's how I wrote them 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 resulting code works as intended but there's something I want to clarify. As you can see, I can get rid of the entire promise syntax for logout
function. However when it comes to the login
function, I was unable to do so. I had to wrap the promise separately and await the result of that. As far as I researched, this seems to be common practice for callback taking functions.
Can somebody shed some light on why is it not possible to get rid of the Promise syntax completely on the login
function?
The reason you don't need to wrap the
FB.logout
function in a Promise wrapper is because you are not using the resolved value ofFB.logout
which you are basically "firing and forgetting". You could write the same method without like below to have the same effect:And because you need the value resolved by
FB.login
, you have to wrap it in aPromise
to use it withasync/await
.