Skip to content

Instantly share code, notes, and snippets.

@michaelwclark
Last active April 8, 2018 22:34
Show Gist options
  • Select an option

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

Select an option

Save michaelwclark/dcf413982fe7876b707253343028c03a to your computer and use it in GitHub Desktop.
Promise + Callback Example
// Our example function to create and populate a user on 2 apis.
function createAndPopulateUserObject (successCallback, errorCallback) {
const A_createUser = mockAPICallPromise({ body: { id: 1 } })
// Functional programing no no, shouldn't need to update outer scope,
// but not a lot of options here.
let A_userID
let B_userID
// Create user on API A
A_createUser.then(resp => {
A_userID = resp.body.id
// Create user on API B
return new Promise((resolve, reject) => {
mockAPICallPromise({ body: { B_userID: '000001' } })
.then(resolve) // success, move on
.catch(error => {
// error creating on API B
deleteUserA(A_userID)
reject(error)
})
})
})
.then(resp => {
// Update API A with ID from API B
B_userID = resp.body.B_userID
return new Promise((resolve, reject) => {
mockAPICallPromise({ body: { A_userID, B_userID } })
.then(resolve) // success, move on
.catch(error => {
// error updating API A
deleteUserA(A_userID)
deleteUserB(B_userID)
reject(error)
})
})
})
.then(resp => {
successCallback({ A_userID, B_userID })
})
.catch(error => errorCallback(error))
}
createAndPopulateUserObject(console.log, console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment