Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Promises, async, and await in ReScript (with Bun!)

Posted on Sep 26 Rescript is "Fast, Simple, Fully Typed JavaScript from the Future"Let's take a look at how to use JavaScript promises, async, and await in ReScript using Bun v1 to quickly run and see our changes.ReScript is a strongly typed language with a JavaScript like syntax that compiles to JavaScript. We'll be using Bun as our package manager and to run our code as we work.Create a bsconfig.json file to configure ReScript:Create a src/index.res file that logs something to the console:Run bun rescript build -w in one terminal tab or window and bun --watch src/index.mjs in another.You now have ReScript quickly compiling the .res file into a .mjs file in a few milliseconds and then Bun running that code in a few milliseconds. This is a very nice quick feedback loop to use for rapid development.I will assume you have a basic working knowledge of Promises in JavaScript.Here's a really basic example of a Promise in ReScript:Let's walk through each part of the code here.Let's start by understanding what's going on with main and the let _ = part.In ReScript every line of code is an expression and the last expression in a function is the return value.Note: even though we aren't adding type annotations, ReScript is able to always correctly infer the types so this function has a type signature of unit => int. unit in ReScript means that we have no value at all, so this function takes in no parameters and returns an int.Any top level expression has to have a type of unit in ReScript, which means we can't return something in a top level function call like what we are doing with main(). So our we have to make sure it returns a type of unit and we can do that by assigning the value to _. _ is a special syntax for a value that exists but we never intent to use. If we did let x = ... the compiler would warn us that x is never used.Creating the promise looks identical to JavaScript:The next part is different from JS. In ReScript we don't have dot style chaining so we can't do Promise.resolve(42).then(...). ReScript has pipes, which we use with the -> operator. So we take the Promise we created and "pipe" it into the next step, which is Promise.then.And inside Promise.then we are logging to the console and returning the result (which is unit) as a Promise. In ReScript every Promise.then has to return another Promise. JavaScript Promises do some magic to handle returning a value or another Promise inside of .then, and since a type can only every be one thing in ReScript we have to commit to always explicitly returning a Promise. Thankfully the Promise module has a thenResolve function that can clean this up.This function can never throw an error so we don't need to worry about .catch so we can safely convert it to async/await syntax. If you want to avoid runtime errors you shouldn't use async/await unless you want to wrap it in a try/catch block, which can get ugly real quick.In ReScript async/await works pretty much the same as in JavaScript. Since we're now expecting main() to return a Promise we can remove the let _ = ... part and replace it with await.Instead of returning a static number and logging it let's take in a number and validate that it is between 0 and 100. If it's out of bounds we want to return an have it log an error.We should see 10 is a valid number! in the Bun console, but we didn't properly handle the error if we give it an invalid number so we get a runtime exception.We can improve this by using ReScript's Result type, which is a variant type that is either Ok or an Error.You should now have a basic understanding of how to use Promises in ReScript. The part that I think is key is that we don't have to throw errors in our promises because we have the Result type. It's a better developer and user experience to capture known errors and handle them gracefully by returning an it in an API response or rendering an error to a user in a React application. Unknown exceptions will happen of course, but in this case we expect that the number could be invalid. What if our function was defined here and meant to used somewhere else? Let's rewrite it to return either return the number or an error message.Now the function will return promise> so anyone using this knows that we expect an error case and can handle it appropriately.We can even make the error messages have more meaning if we change this to use pattern matching:This would allow us to show a meaningful error message to a user if they try and do something invalid.Please feel free to ask anything in the comments!Templates let you quickly answer FAQs or store snippets for re-use.Thanks for a great article!I'd like to add two things I think is cool about async/await in ReScript:This will compile to a try/catch in JS that will handle any async error, and at the same time letting your ReScript code stay really succinct.Thanks again for the great article!Today I learned! I am constantly impressed by how much you can do with pattern matching in this language. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Andrew Lee - Sep 22 ANUHASDEV - Sep 21 Alfonsina Lizardo - Sep 25 lola lollita - Sep 20 Once suspended, jderochervlk will not be able to comment or publish posts until their suspension is removed. Once unsuspended, jderochervlk will be able to comment and publish posts again. Once unpublished, all posts by jderochervlk will become hidden and only accessible to themselves. If jderochervlk is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to Josh Derocher-Vlk. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag jderochervlk: jderochervlk consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging jderochervlk will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Promises, async, and await in ReScript (with Bun!)

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×