Skip to content
Advertisement

how to chain async methods

The API I’ve written has several async methods that do not return a value, but still should be executed in the order they are called. I’d like to abstract the awaiting resolution from the end user so that they can chain method calls and expect that each promise is executed after the previous is resolved like so:

JavaScript

It is not important that we get a value from these methods, just that they are executed in order. I have tried using a linked structure, but it hasn’t been reliable.

JavaScript

The doAsync methods would all defer to _chain like so

JavaScript

I know I could write it like this

JavaScript

And use it like this

JavaScript

But explicitly returning the this object from each then call is what I want to avoid if I can, it just doesn’t seem as clean as the synchronous way of api.doAsync().doAnotherAsync()...

Advertisement

Answer

You can start with a simple wrapper around a Promise

JavaScript

We can add other functions that do more useful things. Note because we’re using Promises, we can sequence synchronous or asynchronous functions with ease

JavaScript

Add whatever functions you want now. This example shows functions that actually do something more realistic

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement