DEV Community

Discussion on: Clarifying Async and Promises

Collapse
rhymes profile image
rhymes • Edited on

Thanks Daniel, for the refresh. I still haven't quite internalised JavaScript promises completely so fresh takes are always welcome.

I was also exploring the other day the possibilities beyond the "then/catch" pattern with promises because to me it still looks like callbacks, neater and cleaner but there has to be a better way, for readability's sake.

In Python land (see the Twisted framework which influenced Node.js) this problem has been already met. In Twisted promises are called "deferreds" but the issue is the same: cascading callbacks, error handlers, callbacks to your error handlers, sibling callbacks and error handlers can still become a mess to read and understand:

.then(() => {}).then(() => {}).then(() => {}).catch((err) => {})

or in Twisted

.addCallback(function).addCallback(function).addCallback(function).addErrback(errHandler)

What they came up with is:

a decorator named inlineCallbacks which allows you to work with Deferreds without writing callback functions.

So in Twisted you can do this:

@inlineCallbacks
def getUsers(self):
    try:
        responseBody = yield makeRequest("GET", "/users")
    except ConnectionError:
       log.failure("makeRequest failed due to connection error")
       return []

   return json.loads(responseBody)

makeRequest returns a deferred (a promise) and this way instead of attaching callbacks and error handlers to it you can wait for the response to come back and if an error arises you handle it there and then with try...except (try/catch in JS). In the latest Python versions you can even do this:

async def bar():
    baz = await someOtherDeferredFunction()
    fooResult = await foo()
    return baz + fooResult

So you can basically use await for the deferred/promises to resolve and write synchronous-looking code instead of attaching callbacks, which brings me back to JavaScript and async/await (same keywords of Python, don't know which came first :D).

Instead of attaching callbacks and error handler to your promise you can use async/await to write more readable code:

async function bar() {
  const a = await someFunction();
  const b = await someOtherFunction();
  return a + b;
}

I found this video by Wes Bos very informing:

ps. this should probably be a separate post since it's so long :-D

Collapse
warrend profile image
Daniel Warren Author

Thanks for this. Great stuff!