How do I transition this promise from deferred style to ES6 style in JavaScript?

Make sure to take a look at Rookie mistake #4: using "deferred" in Nolan Lawson's insightful article titled We have a problem with promises (which is definitely worth the read). I used to rely on deferred style promises, but after reading this, I'm trying to avoid them. However, I recently encountered a specific example where I can't seem to figure out an alternative method and find myself compelled to code using deferred. Any advice would be greatly appreciated.

Let's take a look at the example, an angular factory:

function ConfirmModal($q, $modal) {
    return {
        showModal: function _showModal(options) {
            var _modal = $modal(options)
            var deferred = $q.defer()

            _modalScope.confirm = function(result) {
                deferred.resolve(result)
                _modal.hide()
            }

            _modalScope.cancel = function(reason) {
                deferred.reject(reason)
                _modal.hide()
            }

            return deferred.promise
        }
    }
}

I've omitted some details unrelated to this discussion (such as the implementation of _modalScope), but essentially, the concept is: $modal provides a UI widget with two buttons - Confirm and Cancel. Clicking Confirm calls _modalScope.confirm to resolve the deferred promise, while clicking Cancel calls _modalScope.cancel to reject it.

I attempted rewriting it using

return $q(function(resolve, reject) { ... })
, but I'm unsure of when and how to call resolve and reject within this constructor since the actual logic resides in the _modalScope.confirm/cancel methods. I've been grappling with this issue for days and would really appreciate some assistance.

Thank you!

Answer №1

Assuming the code snippets in your query are operational and _modalScope can be accessed within the function _showModal(), the following code snippet should provide a solution to your query:

function DisplayModal($q, $modal) {
    return {
        displayModal: function _showModal(options) {
            return $q(function(resolve, reject) {
                var _modal = $modal(options)

                _modalScope.confirm = function(result) {
                    resolve(result)
                    _modal.hide()
                }

                _modalScope.cancel = function(reason) {
                    reject(reason)
                    _modal.hide()
                }
            });
        }
    }
}

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

Utilize Express.js to load a random HTML page

Hey there, it's Nimit! I could really use some assistance with my code. I'm trying to figure out if it's possible to load different HTML pages on the same URL like www.xyz.com/home/random. Can more than one HTML page be randomly loaded? I ...

Using Angular.js directive to dynamically set the template URL

In the template for a routeProvider, I have a custom tag that calls for a directive template. The value of the version attribute is determined by the scope and selects the appropriate template. <hymn ver="before-{{ week }}-{{ day }}"></hymn> ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

What is the best way to create hover effects on buttons in Vue.js 3?

I'm currently developing a calculator to practice my Vue.js 3 skills (I am new to vue). I've successfully implemented the basic features, but now I'm exploring how to incorporate hover animations on the buttons. Specifically, I want to diffe ...

Steps to trigger a Bootstrap modal when the user clicks anywhere on the webpage

I need assistance with setting up a Bootstrap dialogue modal to open at the clicked position on a mousedown event when a user interacts with the page. Despite my attempts, the dialogue modal is not opening where it should be. Here's what I've tri ...

Could you provide some advice for creating a Single Page website?

I am working on a simple HTML setup with various elements such as a navbar and content blocks. <html> <head> <title>My HTML5 App</title> <meta charset="UTF-8"> <meta name="viewport" content="wid ...

Is there a way to integrate Prettify with Blogger/BlogSpot?

I am currently utilizing blogger.com as a platform to showcase programming texts and I am interested in incorporating Prettify (similar to Stack Overflow) to enhance the appearance of my code samples. What is the best method for installing the Prettify sc ...

Comparing Angular's Ng-if with Ng-include

When it comes to displaying route views, is it preferable to use: obj = { contact:true,about:false }; <div ui-view="contact" ng-if="obj.contact"></div> <div ui-view="about" ng-if="obj.about"></div> or <div ui-view="contact" ng ...

Guide on building an API that, once authenticated through LinkedIn, provides access to a person's complete list of connections

I'm currently working on creating an application that uses LinkedIn for authentication. Upon successful authentication, the app will retrieve the connections of the user who authenticated. ...

PHP: Safely Submitting Scores Using JavaScript

I have developed a PHP file that updates scores in a database. For example: http://domain.com/heli/test.php?id=100001181378824&score=50000 The code in test.php is as follows: mysql_connect(localhost,$user,$password); $id = mysql_real_escape_string($_ ...

Dynamically retrieving markers from the database based on the most recent timestamp of the last loaded batch

I currently have a database where I store marker locations along with their latitude, longitude, type, and timestamp. Right now, my code loads all markers from the database and displays them on the map with different icons based on their type. However, w ...

updating the observable array in rxjs after every iteration

I am facing an issue with updating the status of contracts in my UI. I have an Observable that contains an array of ContractDto, which is displayed in a table using an async pipe. The 'status' column for each contract initially shows 'not pr ...

Fundamental modeling using Node.js with Mongoose

Currently, I am facing a challenge with developing a node.js application. My goal is to create a model for a musical scale that includes a name and a set of associated notes: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ...

How can you maintain the "link" text in a div while removing the final hyperlink?

I am currently designing a breadcrumb navigation for a website. The breadcrumbs are generated using a templating language before the page is displayed. However, after rendering the page, I need to make some adjustments. Instead of using multiple IF/ELSE s ...

Angular 2 Error: Unresolved Promise rejection - Unable to assign value to reference or variable

I'm currently working on an Ionic 2 app that includes a barcode reader feature. However, I encountered the following issue while trying to display data: Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: ; Task: Promi ...

Prevent clients from navigating the block by using AngularJS when they enter a URL in the

Is there a way to prevent navigation when the user types /pricing in the address bar, and only allow navigation when $location.path("/pricing") is triggered? when("/pricing", { templateUrl: "app/components/Pricing/pricing.html", }) I'm l ...

Struggling with a findIndex problem in React and JavaScript

Whenever I receive activeFilters values like this: const filter = [...activeFilters] The findIndex function always returns -1 even when the item I'm searching for exists. However, when I receive it like this, it works? const filter = activeFilters ...

transferring a JavaScript variable to a different PHP page with JavaScript and retrieving the data

How can I pass a JavaScript variable to another page? Here is the code snippet provided: Code ` $('#disInfo').on('click','tr',function(){ var obj = $(this); var result= obj.find('td').eq(1).html(); wi ...

Is there a way for CasperJS to access the underlying PhantomJS objects and references?

Currently, I am in the process of transitioning a script from PhantomJS to CasperJS, and I am curious if Casper offers any references to the Phantom objects it utilizes internally. It is important to note that Phantom provides certain functionalities that ...