首页 文章

如何在Fable F#中预加载图像列表? [关闭]

提问于
浏览
-1

我对F#和寓言都很新 . 我在JavaScript中有以下代码来加载一些图像,然后在它们全部加载时用它们做一些事情:

async function start() {
  async function loadImages(files) {
    let promises = files.map(filename => {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = filename;
        img.onload = () => resolve(img);
      })
    });
    return Promise.all(promises);
  }

  const images = await loadImages(imageFileNames);
  // Do stuff with images
  console.log('images loaded', images);
}
start();

我怎样才能在F#中写这个用于寓言?

我正在使用寓言简单模板(我认为是Fable 1.x而不是新版本2?)

1 回答

  • 0

    这就是我想出来的,尽管我确信有一个更好的方法,但它能完成这项工作:

    let loadImages imageFileNames callback =
        let mutable remaining : int = (imageFileNames |> List.length) - 1
    
        let imagesWithNames =
            imageFileNames
            |> List.map (fun fileName ->
                let img = Browser.document.createElement_img()
                fileName,img
            )
    
        let images =
            imagesWithNames
            |> List.map (fun (_,img) -> img)
    
        for (fileName, img) in imagesWithNames do
            img.onload <- (fun _ ->
                if remaining > 0 then
                    remaining <- remaining - 1
                else
                    callback(images)
                ())
            img.src <- fileName
        ()
    
    // Use with a callback, e.g.
    let imageFileNames = [ "grass.png" ; "hedge.png" ];
    loadImages imageFileNames (fun images -> printfn "%A" images)
    

    这是从这个javascript版本启发/复制:https://stackoverflow.com/a/41170913

相关问题