Skip to content

Instantly share code, notes, and snippets.

@sobiodarlington
Created August 13, 2019 19:21
Show Gist options
  • Save sobiodarlington/126cf7ab004ac4b3c637077a82e819bb to your computer and use it in GitHub Desktop.
Save sobiodarlington/126cf7ab004ac4b3c637077a82e819bb to your computer and use it in GitHub Desktop.
A fix to Unhandled promise rejection error in javascript promises
/**
* @description ### Returns Go / Lua like responses(data, err)
* when used with await
*
* - Example response [ data, undefined ]
* - Example response [ undefined, Error ]
*
*
* When used with Promise.all([req1, req2, req3])
* - Example response [ [data1, data2, data3], undefined ]
* - Example response [ undefined, Error ]
*
*
* When used with Promise.race([req1, req2, req3])
* - Example response [ data, undefined ]
* - Example response [ undefined, Error ]
*
* @param {Promise} promise
* @returns {Promise} [ data, undefined ]
* @returns {Promise} [ undefined, Error ]
*/
const handle = (promise) => {
return promise
.then(data => ([data, undefined]))
.catch(error => Promise.resolve([undefined, error]));
}
// Explanation
// The handle function takes a promise as an argument and always resolves it be returning an array with [data|undefined, Error|undefined].
// If the promise passed to the handle function resolves it returns [data, undefined];
// If it was rejected, the handle function still resolves it and returns [undefined, Error]
// Usage
async function userProfile() {
let [user, userErr] = await handle(getUser());
if(userErr) throw Error('Could not fetch user details');
let [friendsOfUser, friendErr] = await handle(
getFriendsOfUser(userId)
);
if(friendErr) throw Error('Could not fetch user\'s friends');
let [posts, postErr] = await handle(getUsersPosts(userId));
if(friendErr) throw Error('Could not fetch user\'s posts');
showUserProfilePage(user, friendsOfUser, posts);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment