What is the process for incorporating the Angular JS $q service into this specific scenario?

Looking at the example below, it's essential to ensure that the drawFunc method completes before proceeding to add the opacity and ultimately including foregroundPath to the Kinetic layer.

Is there a way to effectively "wait" for the value of foregroundPath before incorporating it into the layer using Angular JS $q service?

var foregroundPath = new Kinetic.Shape({
    x: x,
    y: y,
    drawFunc: function(context){
        context._context.fillStyle = graphic.fill;
        try{
            fabricSVG.render(context);
        }
        catch (TypeError) {
            console.log('Caught TypeError!');
        }
    },
    fill: graphic.fill,
    name: 'graphicMainColor',
    scale: {x: imageScale, y: imageScale},
    rotation: graphic.rotation
});

foregroundPath.opacity(graphicOpactiy);

var imageLayer = new Kinetic.Layer({name: layerName});
imageLayer.add(foregroundPath);
kineticStage.add(imageLayer);

Update #2

@anthony-c - In this scenario, neither the success nor the error callback is being triggered. Instead, I utilized $q.all() as I am also implementing a similar process for a backgroundPath (which is omitted for brevity). The success method consistently executes first in this example. When using console.log(), it becomes evident that the script always executes the success for all promises before proceeding with the drawFunc. Shouldn't the drawFunc be executed before the success method for all promises?

var backgroundPathDeferred = $q.defer();
var foregroundPathDeferred = $q.defer();

// Graphic Shadow Color
var backgroundPath = new Kinetic.Shape({
    x: x - 1,
    y: y - 1,
    drawFunc: function(context){
        context._context.fillStyle = shadowFill;
        try{
            fabricSVG.render(context);
        }
        catch (TypeError) {
            console.log('Caught TypeError!');
            backgroundPathDeferred.reject(TypeError);
        }
        backgroundPathDeferred.resolve();
    },
    fill: shadowFill,
    name: 'graphicShadowColor',
    scale: {x: imageScale, y: imageScale},
    rotation: graphic.rotation
});

// Graphic Main Color
var foregroundPath = new Kinetic.Shape({
    x: x,
    y: y,
    drawFunc: function(context){
        context._context.fillStyle = graphic.fill;
        try{
            fabricSVG.render(context);
        }
        catch (TypeError) {
            console.log('Caught TypeError!');
            foregroundPathDeferred.reject(TypeError);
        }
        foregroundPathDeferred.resolve();
    },
    fill: graphic.fill,
    name: 'graphicMainColor',
    scale: {x: imageScale, y: imageScale},
    rotation: graphic.rotation
});

var promises = {
    'foreground': foregroundPathDeferred,
    'background': backgroundPathDeferred
};
$q.all(promises).then(function(){
    console.log('All promises resolved.', backgroundPath, foregroundPath);
    backgroundPath.opacity(shadowOpacity);
    foregroundPath.opacity(graphicOpactiy);

    var imageLayer = new Kinetic.Layer({name: layerName});
    imageLayer.add(backgroundPath);
    imageLayer.add(foregroundPath);
    kineticStage.add(imageLayer);
    kineticStage.find('.background').setZIndex(9999);
    $('canvas').css({'width': '100%', 'height': '100%'});
}, function(error){
    console.log('Caught error!', error, foregroundPath, backgroundPath);
});

Answer №1

How to achieve this using $q

var foregroundPathDeferred = $q.defer();
var foregroundPath = new Kinetic.Shape({
    x: x,
    y: y,
    drawDeferred: foregroundPathDeferred,
    drawFunc: function(context){
        context._context.fillStyle = graphic.fill;
        try{
            fabricSVG.render(context);
            this.attrs.drawDeferred.resolve();
        }
        catch (error) {
            this.attrs.drawDeferred.reject(error);
        }

    },
    fill: graphic.fill,
    name: 'graphicMainColor',
    scale: {x: imageScale, y: imageScale},
    rotation: graphic.rotation
});
foregroundPathDeferred.promise.then(function(){
    foregroundPath.opacity(graphicOpactiy);
},function(error){
    console.log('Caught error!', error);
});
var imageLayer = new Kinetic.Layer({name: layerName});
imageLayer.add(foregroundPath);
kineticStage.add(imageLayer);

Answer №2

One option is to simply reposition those commands right before drawFunc concludes:

var foregroundPath = new Kinetic.Shape({
    x: x,
    y: y,
    drawFunc: function(context){
        context._context.fillStyle = graphic.fill;
        try{
            fabricSVG.render(context);
            foregroundPath.opacity(graphicOpactiy); // <-- make the move here
            imageLayer.add(foregroundPath);  // <-- and here
        }
        catch (TypeError) {
            console.log('Caught TypeError!');
        }
    },
    fill: graphic.fill,
    name: 'graphicMainColor',
    scale: {x: imageScale, y: imageScale},
    rotation: graphic.rotation
});

var imageLayer = new Kinetic.Layer({name: layerName});
kineticStage.add(imageLayer);

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

I am trying to update the content in ckeditor when a different option is selected, but for some reason it is not working

jquery issue: the jquery that I added and the content doesn't change even though the "alert(model);" works fine <script> $(document).ready(function() { $("select.modele").change(function() { var modele = $(this) ...

Varying ng-click depending on another value

When a user uploads their own photo, I resize the image, add an ng-click attribute, compile it, and append it to a new element. This process is triggered once upon photo upload: var myElement = angular.element(image); // getting the image myElement.attr( ...

Transform your data visualization with Highcharts enhanced with the stylish appearance of DHTML

I am currently using a dhtmlx menu with my charts, specifically the legendItemClick event. It worked perfectly when I was using highcharts 3.0.1. However, after upgrading to version 4.1.7, the function legendMenu_<?=$id?>.showContextMenu(x,y) in the ...

Why is my HTTP request callback not being executed?

I've been trying to send an HTTP POST request to a 3rd-party API using a promise method. Oddly enough, the callback function never seems to run, even though when I test the code on its own, the API call is successful. Node.js and the concept of an e ...

Can state values be utilized as content for Meta tags?

I am looking for a way to display image previews and titles when sharing a page link. In order to achieve this, I am using the Nextjs Head Component. The necessary details are fetched on page load and used as content for the meta attributes. let campaign = ...

unable to utilize react-speech-recognition package

Looking for a simple react package that can convert user audio to text? I recently installed one and tried its basic code example, only to encounter an error message stating "RecognitionManager.js:247 Uncaught ReferenceError: regeneratorRuntime is not defi ...

Extracting the id of an element using jQuery

The desired outcome is for the code to print the id of the selected div, but it's not working as expected. I've reviewed it multiple times but couldn't pinpoint the error. Any assistance would be greatly appreciated. Here is the HTML: < ...

Exploring the meaning behind RxJS debounce principles

Referencing information found in this source: const debouncedInput = example.debounceTime(5); const subscribe = debouncedInput.subscribe(val => { console.log(`Debounced Input: ${val}`); }); When the first keyup event occurs, will the debouncedI ...

Using Ajax to update a MySQL database with an array from jQuery

I need some assistance in updating a MySQL table using data from a jQuery array through AJAX. I've tried searching for similar issues without any luck, possibly due to my lack of familiarity with the correct terms in web development and coding. Allow ...

Tips for converting text from an HTML input field to a JSON file

After designing a form with four text fields and a submit button, my goal is to save the data into a JSON file upon submission. Additionally, I am looking for a way to display all of the JSON data on my webpage. ...

SolidJS seems to be behaving strangely by rendering content twice when incorporating routing

Just diving into SolidJS and came across an issue where my app seems to be rendering twice. I have a hunch that this has to do with how I'm handling routing. To demonstrate the problem, I've put together a simple example: app.tsx import { Suspen ...

What is the reason behind the browser crashing when a scrollbar pseudo-class is dynamically added to an iframe?

1. Insert a new iframe into your HTML: <iframe id="iframe-box" onload=onloadcss(this) src="..." style="width: 100%; border: medium none; "></iframe> 2. Incorporate the following JavaScript code into your HTML file ...

Pass the ASP.NET MVC model onto the AngularJS scope

Here is the code snippet from my view with temporary JavaScript code for testing: I am trying to assign the ASP.NET MVC model (@Model) to the AngularJS scope ($scope.person). Any suggestions on how to accomplish this? Thank you, The View @model MyApp. ...

Having trouble retrieving the value in the success callback of an Angular UI modal

I've been attempting to recreate an issue in Plunker, but have been unsuccessful so far. Even though I have the exact same code, Plunker is behaving differently for some reason. The problem I'm facing is that the "personModified" value is not get ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...

Ubuntu is experiencing a DNS problem. While the URL request works perfectly on MacOSX, it is unsuccessful on Ubuntu

A custom nodeJS script has been developed to utilize the require('request').post() method. The script executes successfully on MacOSX (Travis), however encounters issues on Ubuntu (Travis). To troubleshoot, experimentation with NodeJS 'https ...

CSS translation animation fails to execute successfully if the parent element is visible

Inquiries similar to this and this have been explored, but do not provide a solution for this particular scenario. The objective is to smoothly slide a menu onto the screen using CSS translation when its parent is displayed. However, the current issue is ...

What steps should I take to ensure my .js.erb files are compatible with Rails 7?

I have been following a Rails Tutorial on Building a Link Shortener with Rails 6 and Ruby 2.xx to create an app. However, I am using Rails 7.0.4 and Ruby 3.0.0. I encountered an issue with my create.js.erb file not functioning properly. After some research ...

Learn the process of retrieving JSON objects through AJAX using jQuery

When making a jQuery call to an API website, I receive the results in JSON format: { "results":[ { "user":{ "gender":"female", "name":{ "title":"mrs", "first":"linda", "last":"diaz" }, ...

Managing the synchronization of a time-consuming method in Angular using TypeScript

We are currently utilizing TypeScript and Angular 6 in our development project and have a service class that is injectable: @Injectable() export class ProductService { getAllProducts(): Observable<Product[]> { return this.http.get(' ...