Guide to encapsulating an asynchronous function in a promise

I am in need of wrapping an asynchronous function within a promise to ensure synchronous execution. The reason behind this is that I must obtain a result from the asynchronous function before proceeding with the program's execution.

Below is the relevant section of my code:

export abstract class OperationElement extends Sprite {

    private imagePath;

    abstract setPosition(mousePosition?, backgroundHeight?, backgroundWidth?) : void;

    loadTexture(){
         var _texture = PIXI.Texture.fromImage(this.imagePath);
         this.texture = _texture;
         console.log(this.height);
    }

    setImagePath(path : string){
         this.imagePath = path;
    }
}

The specific line causing the asynchronicity is

var _texture = PIXI.Texture.fromImage(this.imagePath);

Once the texture is loaded, I can acquire its height. However, I require the texture's height before advancing further in the program. How can I encapsulate this in a promise to achieve synchronous operation?

After browsing similar queries, I found that the most relevant ones had outdated and heavily downvoted answers, which makes me hesitant to follow those suggestions.

Answer №1

fetchTexture():Promise<PIXI.Texture> {  
     return new Promise<PIXI.Texture>((resolve, reject) => {
         var img = new Image();
         img.src = this.imgPath;
         img.onload = () => {
             console.log(img.width);
             this.texture = PIXI.Texture.from(img);
             resolve(this.texture);
         }
         img.onerror = e => reject(e);
     });
}

Answer №2

A basic callback function is all you require.

textureReady(){

    console.log( this.texture.height )
    this.texture.off('update', this.textureReady, this);

}

fetchTexture(){
    var _tex = PIXI.Texture.fromImage(this.imagePath);
    this.texture = _tex;

    this.texture.on('update', this.textureReady, this);

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JSX component in next.js cannot be utilized as a user component

I am facing difficulty in getting my mobile menu to function properly. Initially, I attempted to position it above other content using the useEffect hook, but unfortunately, it resulted in breaking the entire project. This is the error message I encountere ...

Error: The variable 'error' could not be located

Below is the code that I am using: $(document).ready(function(){ var callPage = function(){ $.post('/pageToCall.php'); }; setInterval('callPage()', 60000); }); However, I encountered an error stating ReferenceErro ...

Counting words with JavaScript without using an input tag is a useful skill

Is there a way to count the words in a text using only p and span tags, without using input tags? How can this be achieved? <span class="word" id="word">Words Number</span> <p class="any" id="any"> ...

Preventing navigation without using the <Prompt> component in React Router DOM V6

I have recently discovered that in react-router-dom v5, it was possible to utilize the <Prompt> component to prompt the user before a page transition occurs, allowing them to prevent it. However, this feature has been removed in v6 with plans for a m ...

Creating beautiful prints with images

I have been tasked with developing an MVC C# application where the contents of a div are dynamically created using an AJAX call to fetch data from a database. Upon successful retrieval, the content is then displayed as a success message in JavaScript. Here ...

In which situations is it required to specify the return type of a function in TypeScript?

When it comes to making functions in typescript, the language can often infer the return type automatically. Take for instance this basic function: function calculateProduct(x: number, y: number) { return x * y; } However, there are scenarios where dec ...

Error encountered: Unable to assign onClick property to null object

Hey everyone, I'm running into an issue with my JavaScript. It keeps throwing a TypeError: Cannot set properties of null (setting 'onclick') at SignUp.js:4:43 <HTML> <body> <div class="input-box"> <span class="deta ...

Using Javascript to Pass Variables to Ajax with getElementById

Struggling to figure out how to effectively pass a Javascript Variable to Ajax and then post it to PHP? While both the Javascript and PHP code are functioning as expected, the challenge lies in transferring the Javascript Variable to Ajax for subsequent ...

Creating a simple form page using Express JS

I am a beginner in the world of Node Js and Express Js, currently diving into learning from a book titled "Jump Start NodeJs" by Sitepoint. The author has provided a simple Login Form page as an example in the book. However, when trying to implement the co ...

Is jquery.validate showing errors more than once?

For my testing program, I utilize the jquery.validate plugin to validate user input fields. Here is how it's set up: <script src="js/jquery-1.12.4.min.js"></script> <script src="js/jquery-form-3.51.min.js"></script> <script ...

How can I access dynamically created input elements without using $refs, such as getting focus?

Is there a way to handle dynamically created inputs for editing purposes without using jQuery or vanilla JS all the time? Each input element has its own ID and is displayed through v-if when editing is triggered. However, Vue does not recognize them in r ...

Prevent multiple instances of Home screen app on iOS with PWA

There seems to be an issue with the PWA app not functioning properly on iOS devices. Unlike Android, where adding an app to your homescreen will prompt a message saying it's already installed, iOS allows users to add the app multiple times which is no ...

Why does JavaScript often return the constructor of an object instead of false?

Seeking assistance in resolving issues with the functionality of my script. function CatFactory(cat) // Cat constructor { for (y in cats) { if (cats[y].color == cat.color) {return false;} // return false if already in the array ...

Looking for assistance with transferring a data attribute to a form redirection

I'm seeking assistance with a coding dilemma I've encountered. To provide some background, I have a list of items on my website, each featuring a 'Book Now' button that redirects users to different pages. Recently, I incorporated a mod ...

Develop a Vue mixin to enable theme switching in a Vue.js application

I have successfully developed three distinct themes: light, default, and dark. Currently, I am working on implementing a toggle function in the footer section that allows users to switch between these themes effortlessly. Following the guidance provided b ...

"NextAuth encounters an issue while trying to fetch the API endpoint: req.body

Trying to implement authentication in my Next.js app using NextAuth.js, I've encountered an issue with the fetching process. Here's the code snippet from the documentation: authorize: async (credentials, req) => { const res = await fetch ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

ESLint's feature experimentalObjectRestSpread not being applied with expected behavior

ESLint is showing an unexpected token error, specifically error Parsing error: Unexpected token .., and I'm struggling to identify the root cause. In my .eslintrc.js file, I have: module.exports = { extends: "devmountain/react-config" , rul ...

Exploring TypeScript interfaces with optional properties and returning types

As a newcomer to TypeScript, I am currently exploring the documentation and came across an example in the "Optional Properties" section that caught my attention: interface SquareConfig { color?: string; width?: number; } function createSquare(config: ...

In jQuery, conditionally nest divs within another div based on a specific requirement

There is a container with multiple nested elements that need to be rearranged based on the value of their custom attribute. The goal is to reorder those elements at the end of the container if their 'data-keep-down' attribute is set to true, usin ...