When writing F# for Fable, when should I use async and when should I use promise?

Viewed 1906

F# with Fable provides two computation expressions for working with callback based code: async and promise.

async is more idomatic F#, but it is not clear to me how well it will work in the browser. Ideally I would be able to use async everywhere, since this gives me greater code reuse across client & server.

  • What are the limitations of async in the browser?
  • What are the limitations of promise on the server (e.g. dotnet core)
  • Can I easily switch between the two? (e.g. to wrap fetch API)
  • What is idomatic for Fable?

Note: I do not need to interop with any JavaScript, aside from the browser API.

1 Answers

What are the limitations of async in the browser?

When using async in the browser, you can't use Async.RunSynchronously. I think this is a limitation because JavaScript is single-threaded.

What are the limitations of promise on the server (e.g. dotnet core)

You can't use promise on the server because .Net or .NetCore doesn't know this computation. When working with asynchronous code on a .Net or .NetCore server you need to use async.

If the server, is using Node.js the same limitation applied as in the browser.

Can I easily switch between the two? (e.g. to wrap fetch API)

The fetch API has already been wrapped using promise in Fable.Fetch and Fable.Promise .

    promise {
        let! res = fetch "http://fable.io" []
        let! txt = res.text()
        // Access your resource here
        Browser.console.log txt
    }

Also by opening Fable.Core you can gain access to Async.AwaitPromise and Async.StartAsPromise.

What is idiomatic for Fable?

Personally, I am using promise only because it's a native feature from JavaScript now and in general JavaScript library expects you to work using promise even if you can move between promise and async.

Related