Created
April 9, 2018 03:36
-
-
Save michaelwclark/293bb896608173cdfcf67d11f5189201 to your computer and use it in GitHub Desktop.
Async Destructuring after refactor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // This helper method will allow us to capture succes and error | |
| const ad = async promise => { | |
| const [err, resp] = await promise.then(x => [{}, x]).catch(x => [x, {}]) | |
| const [{ message }, { body }] = [err, resp] | |
| return [message, body] | |
| } | |
| // Simply returns what you pass in as promise form. Will reject if 2nd param | |
| // isn't null. Will resolve valued passed in otherwise. This is only for demonstration. | |
| const mockAPICallPromise = (retVal, error = null) => | |
| new Promise((resolve, reject) => (error && reject(error)) || resolve(retVal)) | |
| const throwOrReturn = (err, val) => err ? throw err : return val | |
| async function createUserA(){ | |
| const [err, id] = await ad(mockAPICallPromise({ body:{id: 1 }})) | |
| return throwOrReturn(err, id) | |
| } | |
| async function createUserB(){ | |
| const [err, id] = await ad(mockAPICallPromise({ body:{id: '000001' }})) | |
| return throwOrReturn(err, id) | |
| } | |
| async function updateUserA(A_userID, B_userID){ | |
| const [err, id] = await mockAPICallPromise({body:{ A_userID, B_userID }}) | |
| return throwOrReturn(err, id) | |
| } | |
| async function createAndPopulateUserObject (successCallback, errorCallback) { | |
| let A_userID, B_userID | |
| try{ | |
| A_userID = await createUserA() | |
| B_userID = await createUserB() | |
| await updateUserA(A_userID, B_userID) //don't care about return, only that it doesn't throw | |
| successCallback({ A_userID, B_userID }) | |
| }catch (e){ | |
| errorCallback(e) | |
| A_userID && deleteUserA(A_userID) | |
| B_userID && deleteUserB(B_userID) | |
| } | |
| } | |
| createAndPopulateUserObject(console.log, console.error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment