Skip to content

Instantly share code, notes, and snippets.

@brunnerh
Created June 17, 2022 13:42
Show Gist options
  • Save brunnerh/ee21fa73baec63e9d833e08bd0756b4d to your computer and use it in GitHub Desktop.
Save brunnerh/ee21fa73baec63e9d833e08bd0756b4d to your computer and use it in GitHub Desktop.
/**
* Function for reading files as promise.
* @param {(reader: FileReader) => void} readCallback
* Execute the read, gets file reader as argument.
* e.g. `r => r.readAsText(file)`
* @returns {Promise<FileReader['result']>}
* Promise that resolves to the file reader result.
*/
export function readFile(readCallback)
{
return new Promise((res, rej) =>
{
const reader = new FileReader();
reader.onload = () => res(reader.result);
reader.onerror = e => rej(reader.error);
readCallback(reader);
});
}
/**
* Load an image as promise.
* @param {string} src The source of the image.
* @returns {Promise<HTMLImageElement>} Promise that resolves to the image object.
*/
export function loadImage(src)
{
return new Promise((res, rej) =>
{
const img = new Image();
img.onload = () => res(img);
img.onerror = e => rej(e);
img.src = src;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment