Natim
Natim

Reputation: 18092

How to handle the result of a list of future with ReasonML?

I am trying to go over a list of items, cache the URL and then update the URL in the list before drawing it.

However I don't seems to be able to do so.

Any idea?

external cache: option(string) => Js.Promise.t({. "uri": string, "filePath": string }) = "get";

let items = result##data##data->Option.getWithDefault([||]);
let cachedUri = items
   ->Belt.Array.map(
         item =>
           cache(item##hosted_video_url)
           ->FutureJs.fromPromise(Js.String.make)
           ->Future.flatMapOk(cachedObj => (
             {. "hosted_video_url": cachedObj##uri }
           )
   ))
   ->Belt.Array.toList
   ->Future.all;

Upvotes: 0

Views: 160

Answers (1)

Natim
Natim

Reputation: 18092

The idea is that you cannot exit a future, so you need to update the state inside the future thing rather than trying to get an equivalent of an asyncio.gather or something similar.

I changed:

setVerticalData(_ => {items-> Js.Array2.sortInPlaceWith((a, b) => {...})});

with

items
  ->List.fromArray;
  ->List.map(item =>
      cache(item##hosted_video_url)
        ->FutureJs.fromPromise(Js.String.make)
   )
   ->Future.all
   ->Future.map(cachedList => {
        setVerticalData(_ => {items: cachedList})
   })

Upvotes: 1

Related Questions