Skip to content

Instantly share code, notes, and snippets.

@guanzo
Last active April 9, 2020 00:15
Show Gist options
  • Save guanzo/0d75cee922dccb7122befb1c5ae49146 to your computer and use it in GitHub Desktop.
Save guanzo/0d75cee922dccb7122befb1c5ae49146 to your computer and use it in GitHub Desktop.

In real code, you would call makePromise().then() or await makePromise(). I assigned the promise to an intermediate variable to illustrate the difference. Which style do you prefer?

const cl = console.log

function thenCatch () {
    cl('start')
    
    const promise = makePromise()

    promise
        .then(response => {
            cl('response')
        })
        .catch(err => {

        })
        .finally(() => {
        
        })
    
    cl('end')
}

thenCatch()
// start
// end
// response
//
// 'response' logged after 'end'. Extremely common source of confusion.

async function asyncAwait () {
    cl('start')
	
    const promise = makePromise()

    try {
        const response = await promise
	cl('response')
    } catch (err) {

    } finally {
    
    }
	
    cl('end')
}

asyncAwait()
// start
// response
// end
//
// Logs are in order. Nice!
@mpedzi03
Copy link

I have just gotten pretty comfortable with the first style, so I would say the first. However, I know as soon as I start using the second, I won't be going back haha. Thanks for the example!

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