re: An async/await gotcha VIEW POST


Really enjoyed the article. Can you clarify what the use case is for duck typing a variable to see if it’s a promise or not?

Because I thought that you can await a non-async function. So if you’re not sure if a function is async, you can await it anyway.

Side note: you could also check if it has a .then property that is typeof function, but again I’m not sure why you wouldn’t just await it as a precaution.

Btw, I’m not in the habit of awaiting every function, but I would do it if the return type is T | Promise<T> since it has the potential of being a promise.


The use case was to create a wrapper for testing purposes, so that we could target parts of the code to wait for in our tests rather than using timeouts etc.

In production, the wrapper does nothing, but we overwrite that behavior in our tests so that we can call await asyncWrapper if needed. I may do an article elaborating on the use case, as it's been a really nice pattern for us.

I'm not sure where the "Duck" line gets drawn in JS, but we were using instanceof Promise because it felt the most direct. Checking for .then and typeof function is even duckier, though as I understand it that's the actual spec!


Cool, yea it would be fun to see an article on that testing scenario.


One could always make new Promise and resolve inside the function that should be 'wrapped as async', and mock it as such. I don't event think setTimeout is necessary. I look forward to hearing test case elaboration as well. :)

code of conduct - report abuse