Async/await to bind JS functions

I started coding my future blog with ReScript to get some experience with it, so I will have a lot of newbie questions :sweat_smile:

Is it possible to use the new async/await syntax to bind functions exported from a JS package?
For example, I have:

import { getDocs } from "firebase/firestore";
const querySnapshot = await getDocs(q);

I wrote the following binding:

@module("firebase/firestore") external get_docs: collection_group => 
    Js.Promise.t<array<DocSnapshot.t>> = "getDocs"

And to use it within my React app, I had to write some code that I still don’t fully understand (but it works!) :grinning_face_with_smiling_eyes:

let _ = 
    get_docs(collection_ref)
    |> Js.Promise.then_(value => {
            value->Js.Array2.forEach((val: DocSnapshot.t) => Js.log2(val.id, DocSnapshot.data(val))
        )

        Js.Promise.resolve(())
})

The question is: is there a way to use async/await in the React code from the binding I wrote?
Thanks!

1 Like

Async/await works like in JS, so you should be able to do the same as in JS:

@module("firebase/firestore") external get_docs: collection_group => 
    Js.Promise.t<array<DocSnapshot.t>> = "getDocs"

let someAsyncFn = async (collection_ref) => {
  let querySnapshot = await getDocs(collection_ref)
}
3 Likes

Thanks!
So I did:

let get_query_snapshots = async (coll) => {
    let query_snapshots = await get_docs(coll)
    query_snapshots->QuerySnapshot.size->Js.log
}

let _ = get_query_snapshots(collection_ref)

and I get the number of docs in the collection.
Is it the right way to do it or is there a way to call the async function immediately after declaring it (like an IIFE in JS)?

It works the same as in JS, so you can do an IIFE just like there, only that you need to take care of the return value in ReScript. So, in the case of an async function, you’ll need to either ignore the promise returned by the function, or assign it to _ like you’re already doing in your example.

Example, but with a non-async function (since that’s not available in the playground yet): https://rescript-lang.org/try?code=BQKABGwJRgvAfGA3uCYCMAmVBfEVoBaeASwHMA7AewCcBTEIA