What is the best way to include a context in a JavaScript promise?

Figuring out JS Promises has always been a challenge for me. I'm aware this might be a basic question, but please bear with me. =) Looking at the code snippet below, my goal is to modify a property within the class containing this function (essentially, I want to reference "this" within the fulfillment methods and have it point back to the class.

I came across suggestions related to setting context, however, they involved closures (()=>{...code..}) which aren't fully compatible with Internet Explorer. Despite our grievances towards that browser, we have to ensure this code functions correctly on IE.

So today, my query is how can I pass a reference to this into the following methods?

var result = this.saveChanges();

return Promise.resolve(result).then(function (value) {
    return value.HasError === false;
}, function (value) {
   if (value && value.responseJSON) {
       return value.responseJSON.HasError === false;
   }
   return false;
});

Your invaluable assistance would be greatly appreciated.

Answer №1

If you want to access this variable within a function, you can declare another variable that references it and use that instead.

var customVariable = this;
var result = this.saveChanges();

return Promise.resolve(result).then(function (value) {
    customVariable.someProperty = true;
    return value.HasError === false;
}, function (value) {
   if (value && value.responseJSON) {
       return value.responseJSON.HasError === false;
   }
   return false;
});

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

Using numerical symbols in multiple tooltips to convert dates into timestamps in the R programming language

When using the highcharter package in R, I am attempting to plot multiple line charts simultaneously. The challenge arises when dealing with different datasets containing values ranging from millions to billions, requiring a numeric symbols formatter imple ...

Is there a way to update a useState in TabPanel without causing a re-render?

For the past few months, I've been immersing myself in React and MUI. Recently, I encountered a problem that has me stumped. The Goal: I receive data from a backend and need to display it for users to edit before sending the changes back to the serv ...

Unlock the full potential of knockout.js by mastering how to leverage templates recursively

Given the following model and view model for nested categories: function Category(id, name) { var self = this; self.Id = ko.observable(id || '00000000-0000-0000-0000-000000000000'); self.Name = ko.observable(name); self.children ...

PugJS is failing to properly interpolate numbers from the JSON file

My goal is to display a list of interfaces retrieved from my router API, which is in JSON format. However, when using Pug, only the strings are being rendered and not the numbers. Here is the output (it displays correctly in HTML): em1 192.168.0.0/24 Addr ...

Guide for displaying d3.js chart using a vue.js method and specifying the target div

I'm working on my Vue code and here's a snippet of what I have: new Vue({ el : '#friendlist', data : { friends : [] }, methods : { fetchStats : function(){ const axios_data = { ...

Mastering Cookies in Javascript

I have been exploring the world of cookies in Javascript and decided to create an experimental log-in page. The page is fully functional, but I am interested in displaying the user's username and password using cookies. Is this possible with Javascrip ...

Identifying the completion of loading a HTML page using an object tag

I am trying to load an HTML page using an object tag, and once the page is fully downloaded, I want to display something. I have attempted the following approach, but it is not working: document.querySelector(".obj_excel").addEventListener("load", funct ...

Executing the event handler only once

In my React project, I have a button that toggles a boolean state. However, I realized that the button can both set and unset the state due to its toggle functionality. I only want the state to be changed once. Is there a different function I can use ins ...

Invalid content detected in React child element - specifically, a [object Promise] was found. This issue has been identified in next js

Why am I encountering an error when I convert my page into an async function? Everything runs smoothly when it's not an async function. The only change is that it returns a pending object, which is not the desired outcome. This is how data is being f ...

Method for transmitting JSON array from Controller to View using CodeIgniter

I have a function in my controller: function retrieveAllExpenses() { $date=$this->frenchToEnglish_date($this->input->post('date')); $id_user=$this->session->userdata('id_user'); $where=array('date&ap ...

AngularJS not passing date data to web API

Greetings! I am currently working on a web application using AngularJS. I have a date value in AngularJS, for example 13-10-2017. In C#, I have the following field: public DateTime LicenseExpiryDate { get; set; } When I send 13-10-2017 in an AJAX reques ...

Is it possible to retrieve JSON data and display only the entries with positive values in an HTML

I am working on a project that involves fetching JSON API data and displaying it in an HTML table, but only for values above 10. Below is the code snippet along with my JavaScript. I specifically want to exclude negative values and only display positive v ...

Locate the initial ancestor element, excluding the parent element that comes before the root ancestor

My HTML structure is as follows: <div> <ul> <li> <div>Other elements</div> <div> <ul> <li class='base-parent parent'> <div>Base Parent ...

Stop Carousel when hovering over individual items (Owl Beta 2)

After creating a unique navigation that is separate from the carousel, I encountered some issues with the autoplay feature. Below is the HTML markup: <div class="carousel"> <div class=""> <img src="assets/img/carousel1.jpg" /&g ...

What is the reason behind JavaScript's `fn.length` returning the count of named parameters that `fn` function has?

Why does calling fn.length in JavaScript return the number of named arguments fn has? > function fn () { } > x.length 0 > function fn (a) { } > x.length 1 > function fn (a,b,c) { } > x.length 3 This behavior is quite peculiar. I wonde ...

Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service : checkIfSymbolExists() { return this.http.get(this.url, { observe: 'res ...

Issue with retrieving the ID of a dynamically created element with jQuery

Whenever I try to execute my function to display the id for a click event of a tag that has items appended dynamically, the alert does not show the id. Instead, it displays 'undefined'. Can anyone help me figure out where I am going wrong? Here ...

How can the Request and Response objects be accessed in external Node.js (Express) files?

My project folder structure is as follows : app Controller testController.js Service testInfoService.js testMoreDataService.js config node-modules public index.js routes routes.js Here is some code : routes.js ro ...

Angular version 8.2 combined with Firebase can result in errors such as those found in the `./src/app/app.module.ngfactory.js` file towards the end of the process when attempting to build with

My first time posing a query on this platform, and certainly not my last. The issue at hand involves the ng-build --prod process failing to complete and throwing errors in my Angular 8.2.14 application. I've integrated Firebase into my project succes ...

Unlock the potential of JavaScript by accessing the local variable values in different functions

I've been struggling for days to find a solution to this issue... https://i.stack.imgur.com/KDN7T.jpg https://i.stack.imgur.com/tOfCl.jpg The image above illustrates the challenge I'm facing - trying to apply data values from elsewhere to the ...