How to write a preload function in Javascript? - javascript

How do I write a function where everything within the function gets loaded before another function is called? For example, (similar to P5.js) I want to implement a preload function that will load anything that needs to be loaded (ie Images) before executing a setup function.
let someImage;
function preload() {
someImage = new Image();
someImage.src = "some URL";
someImage.onload = imageLoaded;
}
function imageLoaded() {
//this is called before setup
}
function setup() {
//I can safely assume everything is properly loaded
}

To preload an image, you need to actually be careful what order you supply the values. If you add src before onload it is possible that the image will load before the onload function will run.
It is annoyingly more possible than it sounds. Same thing goes for <script> as well.
Here's how I would do it:
let someImage;
function preload() {
someImage = new Image();
return new Promise((resolve, reject) => {
// this will pass the event object in the .then function
someImage.onload = resolve;
// Optional if you want to handle images not loading
// someImage.onerror = reject;
someImage.src = "some URL";
});
}
// Now you can do it two ways depending on what floats your boat
// You can change your setup function to be async/await
async function setup() {
try {
let imageResult = await preload();
imageLoaded();
// code that would be in your original setup function
} catch (e) {
// handle error
}
}
// Or you can do promise chaining with callbacks
preload()
.then(loadEvent => imageLoaded())
.then(() => setup());
// .catch(error => handleError(error)); // Optional;

Making sure you assign the Event before the .src, you could execute a function .onload of your image....
function preload(url, doneFunc){
const img = new Image;
img.onload = ()=>{
doneFunc();
}
img.onerror = ()=>{
console.log(img.src+' load failure');
}
img.src = url;
}
preload('yourImg.png', ()=>{
console.log('execute code here');
});
.... or you could use a Promise, like:
function preload(url){
const img = new Image;
const p = new Promise((resolve,reject)=>{
img.onload = ()=>{
resolve();
}
img.onerror = ()=>{
reject(img.src+' load failure');
}
});
img.src = url;
return p;
}
preload('not_a_good_src.png').then(()=>{
console.log('execute code here');
}).catch(error=>{
console.log(error);
});
Of course, I don't recommend loading the images synchronously, when they can be loaded at the same time instead.

using async await you can do it
let someImage="i-m-a--g-e";
let load = true
function preload() {
console.log("running preload",someImage)
return new Promise((resolve,reject)=>{
if(load){ return resolve()}else{return reject()}
}
);
}
function setup(){
console.log("running setup")
}
(async () => {
await preload();
setup();
})();
JavaScript Demo: Promise.reject()

The best way to implement that in Javascript is to have your preload function return a promise, then put all of your code in the promise success return. If you want functions called in a certain order, then you can do a promise chain.
let someImage;
function preload() {
someImage = new Image();
someImage.src = "some URL";
someImage.onload = imageLoaded;
return new Promise((resolve)=>resolve());
}
preload().then(function(){
setup();
});
function setup() {
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://javascript.info/promise-chaining

Related

Is an async function without await keyword equivalent to a function returning a Promise? [duplicate]

The following function takes and image from an url, loads it, and returns its width and height:
function getImageData (url) {
const img = new Image()
img.addEventListener('load', function () {
return { width: this.naturalWidth, height: this.naturalHeight }
})
img.src = url
}
The problem is, if I do something like this:
ready () {
console.log(getImageData(this.url))
}
I get undefined because the function runs but the imaged hasn't loaded yet.
How to use await/async to return the value only when the photo has loaded and the width and height is already available?
How to use async/await to turn this callback function into a promise?
You don't. As usual, you use the new Promise constructor. There's no syntactic sugar for that.
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', () => resolve(img));
img.addEventListener('error', reject); // don't forget this one
img.src = url;
});
}
How to use await/async to log the value only when the photo has loaded and the width and height is already available?
You can do
async function getImageData(url) {
const img = await loadImage(url);
return { width: img.naturalWidth, height: img.naturalHeight };
}
async function ready() {
console.log(await getImageData(this.url))
}
This library works pretty well - it allows connection to the child process or simply returns the result asynchronously if desired: https://github.com/expo/spawn-async

JS Promise wait for nested asynchronous function

I'm having an issue getting 2 asynchronous operations properly timed so the outer function waits for the inner function to finish before continuing. The solution I'm trying to implement is based on an existing solution which uses ES2015, so I can't use await and have to work with Promises.
The solution is split in multiple classes, which for an easy overview I call Main, Invoker and Inner. So the Main class uses an instance of the Invoker to asynchronously execute a command from the Inner class and should then wait for the response, which works but it doesn't wait for the asynchronous Image.onload() from the setSize() of the Inner class.
class Inner extends Component{
setSize(size){
const newImage = { url: null, imageName: canvasImage.imageName};
... some stuff...
const tempImage = new Image();
tempImage.src = canvas.toDataURL();
tempImage.onload = function(){
... some stuff...
const tempCanvas = document.createElement("canvas");
const tempCtx = tempCanvas.getContext("2d");
tempCtx.drawImage(image, x, y, xa, ya);
newImage.url = tempCanvas.toDataURL();
}
return Promise.resolve(newImage);
}
}
class Main{
resize(size){
imageData = this.execute(commandName,'setSize', size);
imageData.then(image => {
... do stuff with image data...
});
}
execute(commandName, ...args) {
return this._invoker.execute(commandName, ...args);
}
}
class Invoker{
execute(...args) {
let [command] = args;
if (isString(command)) {
command = commandFactory.create(...args);
}
return this._invokeExecution(command).then((value) => {
this.clearRedoStack();
return value;
});
}
}
I already tried to move the "return Promise.resolve(newImage) in the setSize Function inside the onload function, but then I'm getting an error in the invoker, because of the missing resolve.
Any ideas?
since the setSize function is using a callback based syntax with onload, you need to wait until the onload function is called by the browser,
you can return a promise from setSize and handle onload for resolve and onerror for reject, something like:
setSize(size){
return new Promise((res, rej) => {
const newImage = { url: null, imageName: canvasImage.imageName};
... some stuff...
const tempImage = new Image();
tempImage.src = canvas.toDataURL();
tempImage.onload = function(){
... some stuff...
const tempCanvas = document.createElement("canvas");
const tempCtx = tempCanvas.getContext("2d");
tempCtx.drawImage(image, x, y, xa, ya);
newImage.url = tempCanvas.toDataURL();
res(newImage);
}
tempImage.onerror = function(error) {
rej(error)
}
})
}
You need to return a promise and resolve it in the onload.
setSize () {
return new Promise((resolve, reject) => {
...
tempImage.onload = function () {
...
resolve(newimage)
}
})
}

Use async/await instead of promise to handle loading an image in Javascript [duplicate]

This question already has answers here:
How to turn this callback into a promise using async/await?
(2 answers)
Closed 3 years ago.
I have written a promise based loading image function.
function loadImage() {
const img = new Image();
return new Promise((resolve, reject) => {
img.addEventListener("load", () => {
resolve();
});
img.addEventListener("error", () => {
reject();
});
img.src = 'assets/myImg.jpg';
});
}
loadImage.then(
() => console.log('image loaded'),
() => console.error('image did not load')
);
I would like to convert it using the async/await but I am actually struggling to do it. Any idea how it can achieved ?
You can await your loadImage function, but the new Image() object doesn't use promises, it uses events which you've wrapped with a Promise.
Inside of an async function, you can await your loadImage function, like so:
async function loadImage() {
const img = new Image();
return new Promise((resolve, reject) => {
img.addEventListener("load", () => {
resolve();
});
img.addEventListener("error", () => {
reject();
});
img.src = 'assets/myImg.jpg';
});
}
async function doSomething() {
try {
await loadImage();
console.log("image loaded");
} catch(e) {
console.error("image did not load");
}
}
With a couple changes you can make it work.
The async await side of things would generally replace the ".then()" chaining.
First of all, keep the loadImage() function as is, and define an additional "async" function to run your async await code in. I've called this "main()". You can then create a variable, for example "loadedImage", and then await the promise function. This will pause execution of the next step (being the console log in this case) until the promise has resolved/rejected and the image is loaded.
async function main() {
let loadedImage = await loadImage();
console.log(loadedImage);
}
main()
Additionally, if you wanted to actually return a value into the loadedImage variable (as right now it will be undefined), inside your promise "resolve()" you can place a value. Eg:
resolve('the image has loaded')

Object keys map - how to pause iteration

I am making a easy html5 game.
Object.keys(gameConfig.playerElems).map((e) =>{
let img = gameConfig.playerElems[e];
let name = e;
let imgObj;
imgObj = new Image();
imgObj.src = img;
imgObj.onload = () => {
playerElemsCounter++;
drawPlayer(imgObj);
}
});
Is it possible to pause .map() iteration while imgObj will be loaded?
Is it possible to pause .map() iteration while imgObj will be loaded?
No. So instead, you use an asynchronous loop. Here's one example, see comments:
// A named IIFE
(function iteration(keys, index) {
// Get info for this iteration
let name = keys[index];
let img = gameConfig.playerElems[name];
let imgObj = new Image();
// Set event callbacks BEFORE setting src
imgObj.onload = () => {
playerElemsCounter++;
drawPlayer(imgObj);
next();
};
imgObj.onerror = next;
// Now set src
imgObj.src = img;
// Handles triggering the next iteration on load or error
function next() {
++index;
if (index < keys.length) {
iteration(keys, index);
}
}
})(Object.keys(gameConfig.playerElems), 0);
But, as Haroldo_OK points out, this will wait for one image to load before requesting the next, which is not only unnecessary, but harmful. Instead, request them all, draw them as you receive them, and then continue. You might do that by giving yourself a loading function returning a promise:
const loadImage = src => new Promise((resolve, reject) => {
const imgObj = new Image();
// Set event callbacks BEFORE setting src
imgObj.onload = () => { resolve(imgObj); };
imgObj.onerror = reject;
// Now set src
imgObj.src = src;
});
Then:
// Load in parallel, draw as we receive them
Promise.all(Object.keys(gameConfig.playerElems).map(
key => loadImage(gameConfig.playerElems[key])
.then(drawPlayer)
.catch(() => drawPlayer(/*...placeholder image URL...*/))
)
.then(() => {
// All done, if you want to do something here
});
// No need for `.catch`, we handled errors inline
If you wanted (for some reason) to hold up loading the next image while waiting for the previous, that loadImage function could be used differently to do so, for instance with the classic promise reduce pattern:
// Sequential (probably not a good idea)
Object.keys(gameConfig.playerElems).reduce(
(p, key) => p.then(() =>
loadImage(gameConfig.playerElems[key])
.then(drawPlayer)
.catch(() => drawPlayer(/*...placeholder image URL...*/))
)
,
Promise.resolve()
)
.then(() => {
// All done, if you want to do something here
});
// No need for `.catch`, we handled errors inline
...or with ES2017 async/await:
// Sequential (probably not a good idea)
(async function() {
for (const key of Object.keys(gameConfig.playerElems)) {
try {
const imgObj = await loadImage(gameConfig.playerElems[name]);
playerElemsCounter++;
drawPlayer(imgObj);
} catch (err) {
// use placeholder
drawPlayer(/*...placeholder image URL...*/);
}
}
})().then(() => {
// All done
});
// No need for `.catch`, we handled errors inline
Side note: There's no point to using map if you're not A) Returning a value from the callback to use to fill the new array map creates, and B) Using the array map returns. When you're not doing that, just use forEach (or a for or for-of loop).

How to turn this callback into a promise using async/await?

The following function takes and image from an url, loads it, and returns its width and height:
function getImageData (url) {
const img = new Image()
img.addEventListener('load', function () {
return { width: this.naturalWidth, height: this.naturalHeight }
})
img.src = url
}
The problem is, if I do something like this:
ready () {
console.log(getImageData(this.url))
}
I get undefined because the function runs but the imaged hasn't loaded yet.
How to use await/async to return the value only when the photo has loaded and the width and height is already available?
How to use async/await to turn this callback function into a promise?
You don't. As usual, you use the new Promise constructor. There's no syntactic sugar for that.
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', () => resolve(img));
img.addEventListener('error', reject); // don't forget this one
img.src = url;
});
}
How to use await/async to log the value only when the photo has loaded and the width and height is already available?
You can do
async function getImageData(url) {
const img = await loadImage(url);
return { width: img.naturalWidth, height: img.naturalHeight };
}
async function ready() {
console.log(await getImageData(this.url))
}
This library works pretty well - it allows connection to the child process or simply returns the result asynchronously if desired: https://github.com/expo/spawn-async

Categories