Skip to content

Instantly share code, notes, and snippets.

@isabellachen
Last active January 3, 2018 19:14
Show Gist options
  • Save isabellachen/fda71d00f6315d5b80bcec38c4e39baf to your computer and use it in GitHub Desktop.
Save isabellachen/fda71d00f6315d5b80bcec38c4e39baf to your computer and use it in GitHub Desktop.
example using setTimeout to create a delayed, async function that is returned in a promise.
//contrived example creating a delayed function and a function that returns a promise where the delayed functio is resolved.
const delay = (cb) => {
setTimeout(() => {
cb('delay over')
}, 2000);
}
const promiseDelay = new Promise((resolve, reject) => {
delay((message)=>{
if (message){
resolve(message)
}else{
reject(Error('it broke'))
}
})
})
//call function using async/ await
const asyncFunc = async () => {
const message = await promiseDelay
console.log(message)
}
//call function using then
promiseDelay.then(data => console.log(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment