Skip to content

Instantly share code, notes, and snippets.

@michaelwclark
Created April 9, 2018 03:36
Show Gist options
  • Select an option

  • Save michaelwclark/293bb896608173cdfcf67d11f5189201 to your computer and use it in GitHub Desktop.

Select an option

Save michaelwclark/293bb896608173cdfcf67d11f5189201 to your computer and use it in GitHub Desktop.
Async Destructuring after refactor
// 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