Skip to content

Instantly share code, notes, and snippets.

@deconstructionalism
Created April 11, 2018 04:40
Show Gist options
  • Select an option

  • Save deconstructionalism/0e8f8f44ba4cba5d30d3b0ef34150ec4 to your computer and use it in GitHub Desktop.

Select an option

Save deconstructionalism/0e8f8f44ba4cba5d30d3b0ef34150ec4 to your computer and use it in GitHub Desktop.
Example of a simple promise and wrapping subsequent async function calls automatically in a promise
const makeAPromise = () => {
return new Promise( (resolve, reject) => {
const statusCodes = [200, 400]
// simulation of an async AJAX request
setTimeout(() => {
// pick a random status after 3 s
const status = statusCodes[Math.floor(Math.random() * statusCodes.length)]
if (status == 200) {
resolve(status)
}
if (status == 400) {
reject(status)
}
}, 3000)
})
}
const myOtherAsyncThing = () => {
setTimeout(() => {
console.log('yay')
}, 1500)
}
makeAPromise().then(res => console.log(`Your request worked fine and got a ${res} code`))
.then(myOtherAsyncThing)
.catch(err => console.error(`Hey, your request crapped out with a ${err} code`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment