What is the best way to modify the value of an external variable within a promise?

var isError = false;
savedata.ingredients.split(',').reduce(function(p, ing) {
      return p.then(function() {
            return db.dog_ingredients.create({ content_name: ing, dogFoodId: dogId });
      });
}, Promise.resolve()).catch(function(e) {
      console.log(e);

      isError = true; ///// I want to modify the value here
});
console.log(isError); // output will be false. 
if(isError){
  res.status(400).send('Error');
}else{
  res.status(200).send('Good');
}

I believe the external variable did not update because the promise is executed asynchronously. I am unsure how to resolve this issue.

Answer №1

It seems like the external variable remained unchanged because the promise operates asynchronously.

Indeed.

I am uncertain about how to resolve this issue.

To address the problem, place the code that assesses the isError variable within a promise callback. It might be beneficial to divide it into two separate then callbacks - one for fulfillment and one for rejection - eliminating the need for the boolean variable altogether.

savedata.ingredients.split(',').reduce(function(p, ing) {
    return p.then(function() {
        return db.dog_ingredients.create({ content_name: ing, dogFoodId: dogId });
    });
}, Promise.resolve()).then(function() {
    res.status(200).send('Good');
}, function(e) {
    console.log(e);
    res.status(400).send('Error');
});

Answer №2

A modification has been made to the value, however this change will not be reflected when logging its current value. The only option is to wait until the promise is either fulfilled or rejected in order to access the updated value.

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

Creating a promise in an AngularJS factory function to perform an operation

When working within an Angular factory, I am tasked with creating a function that must return a promise. Once the promise is returned, additional functionality will be added. SPApp.factory('processing', ['$http', '$rootScope&a ...

Maximizing the versatility of components with styled-components and React: A comprehensive guide to incorporating variants

Currently, I am a novice programmer working on a personal project using React for the front-end. I am looking to create a Button component with the styled-components package that can be easily reused throughout the app with some variations in size, color, ...

Is it possible to update a MobX state when a message is received from Firebase in the background?

I've set up Firebase in my project like this: import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, onMessage, isSupported } from 'firebase/messaging'; import store from './flag'; ...

Having difficulty installing Express MySQL in the designated directory

Attempting to set up express mysql in the specified directory. Encountering an error stating "Sorry, name can only contain URL-friendly characters." Confused about what mistake I might be making. Thanks!!! https://i.sstatic.net/O7lBl.png ...

modify the href target by increasing a variable

Currently, I am in the process of developing a quiz that comes with a timer functionality. The issue arises when the timer finishes; it initiates a scrollLeft animation targeting a specific href. To tackle the problem of always defaulting to the first .qAn ...

The JsFiddle code is malfunctioning

One question I have is about preparing a JSFiddle for a small click program which is not working. It consists of just two lines of code. HTML <body> <button onclick="javascript:launchdialog();">Click Me</button> </body> JavaS ...

Sum values in project pipeline based on conditions with Mongo

I am currently implementing a project pipeline that involves filtering values greater than 100 from fields within an object that is part of an array. Here's an example of the database structure: Database: ---Clients Collection--- client: { _id: ...

When an AJAX request is successful in Angular, utilize the ng-hide directive

I've implemented a feature where double-clicking the name displays an input field, but I'm facing an issue with switching back after a successful put-request. Despite setting $scope.edit to false, it doesn't seem to work as expected. This is ...

My component fails to re-render even after updating the state

For my latest project in React, I decided to create a BMI tracker. The user inputs their weight and height, and the program calculates the BMI. Whenever data is submitted by the user, the application showcases the result and the date of the entry on a grap ...

Updating HTML content based on changes in JSON data using Javascript/Python/d3JS

In my current project, I am able to manipulate a d3JS interface using another platform. The process involves generating data in Python to create JSON, which is then used by d3JS to produce graphics. Finally, the HTML page containing the graphic is loaded l ...

Verifying the size of the unordered list and deleting a list item

I'm attempting to remove the last <li> element from a <ul> element only if it goes beyond a certain length. To achieve this, I have implemented the following code: var selector = "#ulelement" if($(selector).children().length > threshol ...

Tips for automatically refreshing a token with Auth0 on Nuxt without interrupting the user experience

Currently, the platform I'm working on has decided to outsource authentication to a service called Auth0. We were able to successfully set up the login and logout flows by redirecting users to a hosted Auth0 page and then back to our platform after a ...

Seeking methods for fetching data from URL path using React?

When using Express on my server side, I have the following code: app.get('/rooms/:id', function(req, res) { res.sendFile(path.join(__dirname + '/src/index.html')); }); This code sends an index.html file that includes a React c ...

Obtaining an array of objects through the reduction of another array

Currently, my goal is to extract an array of objects from another array. Let's say I have an array consisting of strings: const strArr = ["Some", "Thing"]; The task at hand is to create a new Array containing 2 objects for each st ...

Python script using selenium webdriver to interact with an accordion container and expand its contents (round

After successfully creating a scraper, I encountered an issue where the data I needed to scrape was hidden and required manual expansion before scraping. Upon inspecting the webpage source code, I found that the data was located within 3 different accordio ...

Dealing with file downloads while using JWT-based authentication protocols

Currently, I am developing a web application using Angular that utilizes a JWT token for authentication. This means that every request must contain an "Authentication" header with all the required information. While this method works well for REST calls, ...

Prefer using object destructuring for destructuring purposes

This is my first time coding on Vue.js and I've encountered an issue. Can someone please help me understand the solution or problem? click here to view image ...

Exploring the power of Reactjs and managing server-side data

As a newcomer to the world of Javascript frameworks, I am on the lookout for the perfect framework for my upcoming projects. Up until now, I have been developing simple applications using the MVC framework Django with Bootstrap for the frontend. I apprecia ...

Guide to sending post variables in an AngularJS service

Is there a way to send POST variables to a RESTful API using an angularjs service? I currently have the following setup: angularjsServices.factory('LoginService', [ '$resource', function($resource){ return function(user, pass){ ...

The jQuery function append is functioning properly, however the .html method seems to be malfunctioning when used in

I'm currently utilizing WordPress and have encountered an issue with jQuery().append(response) generating multiple divs. I attempted to use html or innerHtml instead, but it didn't work even though I am receiving a response from the server. ...