Skip to content

Instantly share code, notes, and snippets.

@tarasowski
Last active July 18, 2018 09:25
Show Gist options
  • Save tarasowski/e5f04f8b2f1e6f057db7b5147e40f895 to your computer and use it in GitHub Desktop.
Save tarasowski/e5f04f8b2f1e6f057db7b5147e40f895 to your computer and use it in GitHub Desktop.
#JavaScript - Callbacks vs. Promises

Using Callbacks

const posts = [
    { title: 'Post One', body: 'This is post one' },
    { title: 'Post Two', body: 'This is post two' }
]

const getPosts = () => {
    setTimeout(() => {
        let output = ''
        posts.forEach((post) => {
            output += `<li>${post.title}</li>`
        })
        document.body.innerHTML = output
    }, 1000)
}

const createPost = (post, callback) => {
    setTimeout(() => {
        posts.push(post)
        callback()
    }, 2000)
}

createPost({ title: 'Post three', body: 'This is post three' }, getPosts)

Using Promises

const posts = [
    { title: 'Post One', body: 'This is post one' },
    { title: 'Post Two', body: 'This is post two' }
]

const getPosts = () => {
    setTimeout(() => {
        let output = ''
        posts.forEach((post) => {
            output += `<li>${post.title}</li>`
        })
        document.body.innerHTML = output
    }, 1000)
}

const createPost = (post) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            posts.push(post)
            const error = false
            if (!error) {
                resolve()
            }
            else {
                reject('Something went wrong')
            }
        }, 2000)
    })


}

// createPost({ title: 'Post three', body: 'This is post three' })
//     .then(getPosts)
//     .catch(err => console.log('Something went wrong', err))

// const promise1 = Promise.resolve('Hello One')
// const promise2 = Promise.resolve('Hello Two')
// const promise3 = Promise.resolve('Hello Three')
// const promise4 = fetch('https://jsonplaceholder.typicode.com/users').then(response => response.json())

// Promise.all([promise1, promise2, promise3, promise4]).then(values => console.log(values))

Using Async/Await

const init = async() => {
    await createPost({ title: 'Post three', body: 'This is post three' })

    getPosts()
}

init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment