我对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#编写这些故事以供寓言使用?
我正在使用寓言简单模板(我相信它是寓言1.x而不是新版本2?)
答案 0 :(得分: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