Async Await Chaining

Creating synchronously chained functions is straight forward. Codepen. const UserCollectionSync = { find(id=''){ document.writeln('1'); return this; }, update(){ document.writeln('2'); return this; }, save(){ document.writeln('3'); return this; } } UserCollectionSync .find() .update() .save(); But when we decide to just throw some ‘async’ ‘await’ flags on those functions everything doesn’t work. FOLLOWING CODE IS WRONG: Codepen. // delay is used to represent some asynchronous work function delay(ms){ return new Promise(resolve => setTimeout(resolve, ms)); } //end delay() const UserCollectionAsync = { async find(id=''){ await delay(1000) document.writeln('1'); return this; }, async updateFor(options={}){ await delay(50); document.writeln('2'); return this; }, async save(){ await delay(50); document.writeln('3'); return this; } } UserCollectionAsync .find() .updateFor('') .save(); The reason it fails is because when the ‘find()’ is called it returns a promise that hasn’t resolved instead of the ‘UserCollectionAsync’ object (Factory pattern.) Therefor you can’t find a function ‘update()’ on a promise. One common way of solving the issue is by allowing the factory to maintain a queue and force the user to add ‘done()’ at the end of the chain: Codepen. ...

January 6, 2019 · 3 min