Is async/await no place in functional programming

2019-07-23 03:12发布

问题:

I am learning monad with JavaScript. Promise itself is monad, and is the right way to handle async side effects functionally. How about the es7 new player async/await, can we use it in functional programming of JavaScript? I feel like it falls well defined promise monad back to imperative way. Or there is a way to use async/await wisely enough to make function programming even easier?

回答1:

You still can write asynchronous code in a functional style with it. async/await is nothing but sugar, just like do notation is in Haskell (though it is restricted to promises and not generic monads). If you are writing code with promises and feel that async/await would simplify it, then use it.

Notice that promises are often using side-effects (and asynchrony itself, by being in the time domain, might count as an effect), so an imperative style is often not the wrong approach. After all, even functional programs carry out side effects.