SHARE
TWEET

Untitled

a guest Aug 25th, 2019 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * @description ### Returns Go / Lua like responses(data, err)
  3.  * when used with await
  4.  *
  5.  * - Example response [ data, undefined ]
  6.  * - Example response [ undefined, Error ]
  7.  *
  8.  *
  9.  * When used with Promise.all([req1, req2, req3])
  10.  * - Example response [ [data1, data2, data3], undefined ]
  11.  * - Example response [ undefined, Error ]
  12.  *
  13.  *
  14.  * When used with Promise.race([req1, req2, req3])
  15.  * - Example response [ data, undefined ]
  16.  * - Example response [ undefined, Error ]
  17.  *
  18.  * @param {Promise} promise
  19.  * @returns {Promise} [ data, undefined ]
  20.  * @returns {Promise} [ undefined, Error ]
  21.  */
  22. const handle = (promise) => {
  23.   return promise
  24.     .then(data => ([data, undefined]))
  25.     .catch(error => Promise.resolve([undefined, error]));
  26. }
  27.  
  28. // Explanation
  29. // The handle function takes a promise as an argument and always resolves it be returning an array with [data|undefined, Error|undefined].
  30.  
  31. // If the promise passed to the handle function resolves it returns [data, undefined];
  32. // If it was rejected, the handle function still resolves it and returns [undefined, Error]
  33.  
  34. // Usage
  35. async function userProfile() {
  36.   let [user, userErr] = await handle(getUser());
  37.  
  38.   if(userErr) throw Error('Could not fetch user details');
  39.  
  40.   let [friendsOfUser, friendErr] = await handle(
  41.     getFriendsOfUser(userId)
  42.   );
  43.  
  44.   if(friendErr) throw Error('Could not fetch user\'s friends');
  45.  
  46.   let [posts, postErr] = await handle(getUsersPosts(userId));
  47.  
  48.   if(friendErr) throw Error('Could not fetch user\'s posts');
  49.  
  50.   showUserProfilePage(user, friendsOfUser, posts);
  51. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top