- Notifications
You must be signed in to change notification settings - Fork2.4k
Description
One of the elephants in the room is the newasync/await support that has come to Node and Chrome, and will soon hit every other major browser. I've been thinking about what Async can do in theasync/await world.
Currently, we can adaptasync functions by wrapping them withasyncify. Since anasync function is essentially just a function that returns a Promise, that old adapter can easily convert it to a callback-style function. However, it leads to the somewhat absurd looking:
async.mapLimit(arr,10,async.asyncify(async(val)=>{letfoo=awaitdoSomething(val);//...returnbar;}),done);
However, one of the features in the spec forasync functions is that:
Object.getPrototypeOf(asyncFn)[Symbol.toStringTag] === "AsyncFunction"This gives a way to easily detect (native)async functions. We could use this technique to automaticallyasyncify them. The example above becomes:
async.mapLimit(arr,10,async(val)=>{letfoo=awaitdoSomething(val);//...returnbar;},done);
...which seems to flow much more naturally. I also think we should continue to use callbacks. If a user wanted toawait the result, they would have topromisify the function, orpify Async as a whole:
letresult=awaitpify(async.mapLimit)(arr,10,async(val)=>{letfoo=awaitdoSomething(val);//...returnbar;});
The above method for detectingasync functions only works with native functions. I don't think there is a way to detect Babel transpiled functions. We certainly can't detect normal functions that simply return Promises, because we'd have to retroactively not pass a callback. There would he a huge caveat that this would only work without a transpiler in very modern environments, otherwise you still have to manually wrap withasyncify.
Also, admittedly, many Async methods don't make sense withasync/await. Most of the control flow methods (save for things likeauto andqueue) are more easily replicated with native control flow constructs.map andparallel can be replaced withPromise.map andPromise.all. However, the limiting collection functions would be very useful, as well asauto and a few others. (Also,autoInject withasync functions is a async control flow dream!)